这里的脚本工作正常,如果数据库中没有记录,我会在页面上收到以下错误
SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法中有错误;检查与MySQL服务器版本对应的手册,以便在第1行的“-5”附近使用正确的语法
这里是php和mysql部分
try {
require_once 'db.php';
$total = $db->query('SELECT COUNT(*) FROM article')->fetchColumn();
$per_page = 5;
$pages = ceil($total / $per_page);
$page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
'options' => array(
'default' => 1,
'min_range' => 1,
),
)));
$offset = ($page - 1) * $per_page;
$start = $offset + 1;
$end = min(($offset + $per_page), $total);
$stmt = $db->prepare('SELECT * FROM article ORDER BY ne_title LIMIT :limit OFFSET :offset');
$stmt->bindParam(':limit', $per_page, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
if ($stmt->rowCount() > 0) {
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$iterator = new IteratorIterator($stmt);
foreach ($iterator as $row) {
$desc = $row["ne_article"];
$img = $row['ne_image'];
if(!empty($img)){
$img = '<br/><img src="uploads/images/'.$img.'" alt="" class="responsive-shrink">';
}else{
$img = '';
}
$youtube = $row["ne_youtube"];
if(!empty($youtube)){
$youtube = '<br/><div class="video-container"><iframe src="http://www.youtube.com/embed/'.$youtube.'"></iframe></div>';
}else{
$youtube = '';
}
echo '<h4><a href="'.$row['ne_url'].'">'.$row['ne_title'].'</a></h4>
<h5><b>Views:</b> '.$row['views'].', <b>Posted on:</b> '.format_date($row['created']).'</h5>
'.$img.'
'.$youtube.'
<p>
<br/>'.bbcode(nl2br(shortenString($desc))).'
</p>
<div id="pagelink">
<a href="'.$row['ne_url'].'" class="myButton"> Read more...</button></a>
</div>';
}
echo '<div id="pagination">
<div id="pagiCount">';
$prevlink = ($page > 1) ? '<span id="prev"><a href="?page=1" title="First page">First</a></span> <span id="prev"><a href="?page=' . ($page - 1) . '" title="Previous page"><<</a></span>' : '';
$nextlink = ($page < $pages) ? '<span id="next"><a href="?page=' . ($page + 1) . '" title="Next page">>></a></span> <span id="next"><a href="?page=' . $pages . '" title="Last page">Last</a></span>' : '';
echo '<div id="paging"><p><small>', $prevlink, ' Page ', $page, ' of ', $pages, '', $nextlink, '</small></p></div>';
echo '</div></div>';
} else {
echo '<p>No resilts found.</p>';
}
} catch (Exception $e) {
echo '<p>', $e->getMessage(), '</p>';
}
有人可以帮忙解决这个问题吗?
答案 0 :(得分:0)
我觉得你过度复杂化了。试试这样的事情,注意我已经绑定了$ start和$ end而不是你的$ limit变量。由于你的其他代码,开始永远不会是负数或零......
$total = $db->query('SELECT COUNT(*) FROM article')->fetchColumn();
$per_page = 5;
$pages = ceil($total / $per_page); // total number of pages
$offset = ($page - 1) * $per_page;
$start = $offset + 1;
$end = min(($offset + $per_page), $total);
$stmt = $db->prepare('SELECT * FROM article ORDER BY ne_title LIMIT :limit OFFSET :offset');
$stmt->bindParam(':limit', $start, PDO::PARAM_INT);
$stmt->bindParam(':offset', $end, PDO::PARAM_INT);