【问题标题】:Prepared statement limit not working even with emulate prepares turned off即使关闭了模拟准备,准备好的语句限制也不起作用
【发布时间】:2014-04-05 02:45:03
【问题描述】:

我的查询

$stmt = $db->prepare('SELECT * FROM generalevent ORDER BY date DESC LIMIT ?, 25');
$stmt->execute(array( $limit ));

消息一直失败

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 '?, 25' at line 1' 
in ../test.php:35 
Stack trace: #0 ../test.php(35): PDO->prepare('SELECT * FROM g...') #1 {main}

我已经有了

$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

所以根据我的阅读,这应该可以,不是吗?

【问题讨论】:

  • $limit 是如何定义的?
  • @Fred-ii- $limit = $currPage*25; 它的类型是integer,我检查了gettype
  • @PatrickQ 仅供参考:date 不是保留字。
  • @gta0004 你可以试试$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);DESC LIMIT %d, 25'

标签: php mysql pdo


【解决方案1】:

以下内容对我有用,但是很难给出明确的答案,因为没有提供完整的代码。

这是我在我自己的服务器上从现有表中测试的内容。

旁注:LIMIT 之后使用:limit? 都有效并且没有抛出任何错误。

<?php
$mysql_username = 'xxx'; // for DB
$mysql_password = 'xxx'; // for DB

try {

$pdo= new PDO('mysql:host=localhost;dbname=database_name', $mysql_username, $mysql_password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );

} catch (PDOException $e) {
     exit( $e->getMessage() );
}

try {

$currPage = 2;

// $limit = 1;

$limit = $currPage * 25;

$sql = "SELECT * FROM animals LIMIT :limit,25";

$stmt = $pdo->prepare($sql);
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->execute();

     $results = $pdo->query($sql);

//     print_r($results);
} catch (PDOException $e) {
     echo $e->getMessage();
}

    $cols = $results->columnCount(); // Number of returned columns

    echo 'Number of returned columns: '. $cols. '<br />';

echo '

<div align="center">
  <center>
  <table border="1" cellspacing="0" cellpadding="3">
    <tr>

      <td width="10%" bgcolor="#99CCFF"><p align="center">ID</td>
      <td width="33%" bgcolor="#99CCFF"><p align="center">Breed</td>
      <td width="34%" bgcolor="#99CCFF"><p align="center">Species</td>
    </tr>

';

foreach($results as $row) {

echo "<tr><td width=\"10%\"><p align=\"center\">" . $row['id'] . "</td>\n<td width=\"33%\">" . $row['name'] . "</td><td width=\"33%\">" . $row['species'] . "</td>";

}

echo "\n";
  echo "</tr>";

echo '

  </table>
  </center>
</div>
';

?>

【讨论】:

    猜你喜欢
    • 2014-04-11
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多