参数化查询
我目前正在学习参数化查询,因为使用它们有很多优点。
有人可以通过将此代码块转换为参数化版本来给出一些指示吗?
谢谢。
if(isset($_GET['news_art_id']) && (!empty($_GET['news_art_id'])))
{
$news_art_id = htmlentities(strip_tags($_GET['news_art_id']));
$news_art_id = validate_intval($news_art_id);
//echo $news_art_id;
$_SESSION['news_art_id'] = $news_art_id;
// Assign value to status.
$onstatus = 1;
settype($onstatus, 'integer');
$query = 'SELECT M.id, M.j_surname, M.j_points_count, M.j_level, A.j_user_id,A.id, A.jart_title, A.jart_tags, A.jart_description, A.jart_createddate FROM jt_articles A, jt_members M WHERE M.id = A.j_user_id AND A.id = ' . check_db_query_id($news_art_id) . " AND A.jart_status = $onstatus;";
$result = mysql_query($query) or die('Something went wrong. ' . mysql_error());
$artrows = mysql_num_rows($result);
}
I am currently learning parametrized queries as there are advantages to using them.
Could someone give some pointers by converting this block of code to a parametrized version?
Thanks.
if(isset($_GET['news_art_id']) && (!empty($_GET['news_art_id'])))
{
$news_art_id = htmlentities(strip_tags($_GET['news_art_id']));
$news_art_id = validate_intval($news_art_id);
//echo $news_art_id;
$_SESSION['news_art_id'] = $news_art_id;
// Assign value to status.
$onstatus = 1;
settype($onstatus, 'integer');
$query = 'SELECT M.id, M.j_surname, M.j_points_count, M.j_level, A.j_user_id,A.id, A.jart_title, A.jart_tags, A.jart_description, A.jart_createddate FROM jt_articles A, jt_members M WHERE M.id = A.j_user_id AND A.id = ' . check_db_query_id($news_art_id) . " AND A.jart_status = $onstatus;";
$result = mysql_query($query) or die('Something went wrong. ' . mysql_error());
$artrows = mysql_num_rows($result);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般规则是:每个变量都应该绑定,根本没有内联变量。
技术细节:http://php.net/manual/en/pdo.prepare.php< /a>
The general rule is: Every variable should be binded, no inline variables at all.
Technical details: http://php.net/manual/en/pdo.prepare.php
在您的情况下没有优势,请记住参数化查询需要对数据库进行两次调用:一次用于设置查询模板并解析,另一个用于填充查询模板参数,通常在循环时使用。因此,在这种情况下,您最好调用存储过程(始终是最佳选择)或使用内联 sql 并确保使用 http://php.net/manual/en/function.mysql-real-escape-string.php(如果适用)。
in your case there is no advantage, remember a parameterised query requires 2 calls to the db : one to setup the query template and parse, the other to populate the query template params and is typically used when looping. So in this instance you're better off calling a stored procedure (always the best choice) or using inline sql and making sure you use http://php.net/manual/en/function.mysql-real-escape-string.php when applicable.