我正在尝试编写一个小的分页系统,但就事情而言,我收到了一个错误.这是我的代码:
else{
include('head.php');
if(empty($_GET['pg'])){ $_GET['pg'] = 0 ;}
$offset = $_GET['pg'] * 5;
$query = $db->prepare('SELECT * FROM posts ORDER BY id DESC LIMIT 5 OFFSET :n');
$query->bindParam(':n', $offset);
$query->execute();
?>
while ($data = $query->fetch()){
echo ''.$data['content'].'';
}}?>
所以我只想逐页显示5篇文章.也就是说,我想要索引页面上的最后5篇文章(即第0页),然后是第1页上的接下来的5篇文章等等.到目前为止,我得到的只是这个错误:
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 ”0” at line 1’ in /Applications/MAMP/htdocs/index.php:24 Stack trace: #0 /Applications/MAMP/htdocs/index.php(24): PDOStatement->execute() #1 {main} thrown in /Applications/MAMP/htdocs/index.php on line 24
第24行是$query-> execute();指令.
所以我想我的问题是:发生了什么事?我的传呼系统是否按照我想要的方式工作?
解决方法:
您收到此错误是因为生成的sql在0周围有引号字符.
‘SELECT * FROM posts ORDER BY id DESC LIMIT 5 OFFSET:n’
正在变成
‘SELECT * FROM posts ORDER BY id DESC LIMIT 5 OFFSET“0”’
当你需要的SQL是
‘SELECT * FROM posts ORDER BY id DESC LIMIT 5 OFFSET 0’ – 0周围没有引号
试试这个
$offset = (int) ($_GET['pg'] * 5 ); // cast to an int so that you know its not a non-int value, then you don't need the protection of bind
$sql = 'SELECT * FROM posts ORDER BY id DESC LIMIT 5 OFFSET ' . $offset;
$query = $db->prepare($sql);
$query->execute();
标签:php,mysql
来源: https://codeday.me/bug/20190708/1400011.html