2015-06-28 116 views
4

我正在尝试编写一个小小的寻呼系统,但就目前情况而言,我遇到了一个错误。这是我的代码:寻呼和错误

<!-- something before that's working well -->  
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(); 
?> 
<body> 
<?php 
    while ($data = $query->fetch()){ 
     echo '<article>'.$data['content'].'</article>'; 
     }}?> 

    </body> 

所以我只是想显示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();指令。

所以我想我的问题是:发生了什么事?我的分页系统是否按照我想要的方式工作?

回答

1

您收到此错误,因为生成的SQL有引号字符围绕0

'SELECT * FROM帖子ORDER BY ID DESC LIMIT 5 OFFSET:N' 正在变成

“SELECT *来自帖子ORDER BY ID DESC LIMIT 5 OFFSET “0”” 当你需要的SQL是

“SELECT * FROM帖子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(); 
0

也许这样?

$offset = $_GET['pg'] * 5; 
$query = $db->prepare("SELECT * FROM posts ORDER BY id DESC LIMIT 5 OFFSET ':n'"); 
$query->execute(array(':n' => $offset); 

编辑:

OK,这个码应该工作。

$sql = "SELECT `password` FROM `users` WHERE `username` = :username"; 
$stmt = $conn->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY)); 
$query = $stmt->execute(array(':username' => $username)); 
$rows = $query->fetchAll(); 
if (empty($rows)) { 

} 

只需根据您的需要进行修改。

+0

没有,同样的错误,就像在开始时一样... –