0

我最近开始使用 php PDO 来防止 SQL 注入,但我遇到了该语句的问题,因为它会根据我通过 URL 传递的参数来更改页面结果。$_GET['cat_id']我正在努力的部分是当 URL 有 cat_id 到我的执行数组时如何添加for 。这是一个工作版本,但显然很容易发生 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_idurl 中没有,它会失败

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']));
4

1 回答 1

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);
于 2013-05-10T02:46:17.543 回答