我最近开始使用php PDO来防止SQL注入,但是我对语句有问题,因为它会根据我通过URL传递的参数来改变页面结果。我正在努力的部分是当URL有一个cat_id到我的执行数组时,如何添加$_GET['cat_id']
。这是一个工作版本,但很明显很容易注入SQL,提前感谢任何帮助!
PHP
$and = '';
if (isset($_GET['cat_id'])) {
$and = "AND art_cat_id = ".$_GET['cat_id'];
}
$statement_article = $db->prepare("SELECT * FROM app_articles WHERE art_sta_id = :art_sta_id $and ORDER BY art_date DESC");
$statement_article->setFetchMode(PDO::FETCH_ASSOC);
$statement_article->execute(array(':art_sta_id' => "1"));
这是我尝试的内容,但如果网址中没有cat_id
则会失败。
PHP
$and = '';
if (isset($_GET['cat_id'])) {
$and = "AND art_cat_id = :cat_id";
}
$statement_article = $db->prepare("SELECT * FROM app_articles WHERE art_sta_id = :art_sta_id $and ORDER BY art_date DESC");
$statement_article->setFetchMode(PDO::FETCH_ASSOC);
$statement_article->execute(array(':art_sta_id' => "1",':cat_id' => $_GET['cat_id']));
答案 0 :(得分:2)
当有cat_id时调整参数数组:
$and = '';
$params = array(':art_sta_id' => "1");
if (isset($_GET['cat_id']))
{
$and = "AND art_cat_id = :cat_id"
$params[':cat_id'] = $_GET['cat_id'];
}
$statement_article = $db->prepare("SELECT * FROM app_articles WHERE art_sta_id = :art_sta_id $and ORDER BY art_date DESC");
$statement_article->setFetchMode(PDO::FETCH_ASSOC);
$statement_article->execute($params);