php – 如何在pdo-> query中添加变量值

前端之家收集整理的这篇文章主要介绍了php – 如何在pdo-> query中添加变量值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想升级我的当前代码,这是经常用PDO注入的sql.

目前我一直坚持在PDO查询中使用变量.

如果我有这样的两个论点

$rowsPerPage = 3;

  // by default we show first page
  $pageNum = 1; 

  if (isset($_GET['page'])) {
     $pageNum = MysqL_real_escape_string($_GET['page']);
  }

  $offset = ($pageNum - 1) * $rowsPerPage;

我有这样的查询

$STH = $DBH->query("SELECT News.ID,LEFT(NewsText,650),Title,AID,Date,imgID," .
        "DATE_FORMAT(Date,'%d.%m.%Y.') as formated_date " .
        "FROM News,Categories,NewsCheck  WHERE Name LIKE '%News - Block%' AND CID=Categories.ID AND JID=News.ID ". 
        "ORDER BY `Date` DESC LIMIT $offset,$rowsPerPage");

PDO在查询ORDER BY的最后一行报告错误@H_502_12@当我用这些线替换@H_502_12@“ORDER BY Date DESC LIMIT3,3”);一切正常.

那么如何在PDO :: query中添加变量值呢?

更新:@H_502_12@感谢回答,我已经像这样更新了我的代码

$STH = $DBH->prepare("SELECT News.ID," .
            "DATE_FORMAT(Date,'%d.%m.%Y.') as formated_date " .
            "FROM News,NewsCheck  WHERE Name LIKE '%News - Block%' AND CID=Categories.ID AND JID=News.ID ". 
            "ORDER BY `Date` DESC LIMIT :offset,:rowsPerPage;");

$STH->bindParam(':offset',$offset,PDO::PARAM_STR);
$STH->bindParam(':rowsPerPage',$rowsPerPage,PDO::PARAM_STR);

$STH->execute();

但是发生了错误

Fatal error: Uncaught exception ‘PDOException’ with message@H_502_12@ ‘sqlSTATE[42000]: Syntax error or access violation: 1064 You have an@H_502_12@ error in your sql Syntax; check the manual that corresponds to your@H_502_12@ MysqL server version for the right Syntax to use near ”-3’,‘3” at@H_502_12@ line 1’ in /pdo/test.PHP:42 Stack trace: #0@H_502_12@ /pdo/test.PHP(42): PDOStatement->execute() #1 {main} thrown in@H_502_12@ /pdo/test..

第二次更新@H_502_12@像这样从PARAM_STR更改为PARAM_INT

$STH->bindParam(':offset',PDO::PARAM_INT);
$STH->bindParam(':rowsPerPage',PDO::PARAM_INT);

一切正常.

您希望使用预准备语句和查询参数,如下所示:
$sth = $dbh->prepare('SELECT your_column FROM your_table WHERE column < :parameter');
$sth->bindParam(':parameter',$your_variable,PDO::PARAM_STR);
$sth->execute();

即使您使用的是PDO,直接在查询中使用变量也无法保护您免受sql注入的侵害.参数是防止它们的唯一好方法.

猜你在找的PHP相关文章