我想升级我的当前代码,这是经常用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的最后一行报告错误
当我用这些线替换
“ORDER BY Date DESC LIMIT3,3”);一切正常.
那么如何在PDO :: query中添加变量值呢?
更新:
感谢回答,我已经像这样更新了我的代码
$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
‘sqlSTATE[42000]: Syntax error or access violation: 1064 You have an
error in your sql Syntax; check the manual that corresponds to your
MysqL server version for the right Syntax to use near ”-3’,‘3” at
line 1’ in /pdo/test.PHP:42 Stack trace: #0
/pdo/test.PHP(42): PDOStatement->execute() #1 {main} thrown in
/pdo/test..
第二次更新
像这样从PARAM_STR更改为PARAM_INT
$STH->bindParam(':offset',PDO::PARAM_INT); $STH->bindParam(':rowsPerPage',PDO::PARAM_INT);
一切正常.