所以我正在使用php中的分页系统,我到了使用sql从数据库中获取所有帖子的部分这是我的代码:
$sql = 'SELECT * FROM wp_posts WHERE post_parent="0" ORDER BY ID DESC LIMIT $start, $per_page';
$articles = $db->query($sql);
$ start应设置为0,$ per_page设置为20
但是当通过foreach循环运行结果时,它会返回此警告:
警告:第29行的C:\ wamp \ www \ System-tips \ index.php中为foreach()提供的参数无效 调用堆栈
当manualy在sql查询中输入数字时,它运行得很好,我做错了什么?
编辑:这是完整的index.php代码
<?php
include"header.php";
//Delete Auto Draft posts
$del = 'DELETE FROM wp_posts WHERE post_title="Auto Draft"';
$db->query($del);
//Receive all posts
$sql = 'SELECT * FROM wp_posts WHERE post_parent="0" ORDER BY ID DESC';
$counter = $db->query($sql);
//Amount of pages
$row_cnt = $counter->num_rows;
$per_page = 5;
$pages = ceil($row_cnt/$per_page);
//Receive current page
if(!isset($_GET['page'])) {
header("location: index.php?page=1");
}
else {
$page = $_GET['page'];
}
$start = (($page - 1)*$per_page);
$sql = 'SELECT * FROM wp_posts WHERE post_parent="0" ORDER BY ID DESC LIMIT $start, $per_page';
$articles = $db->query($sql);
foreach ($articles as $article) {
echo'
<article>
<h3>'. $article['post_title'] .'</h3>';
search_picture($article['post_content']);
preview($article['post_content']);
echo '<a href="#">Read the article...</a>';
echo'</article>';
}
function search_picture($content) {
$array = explode('<img',$content);
if (isset($array[1])) {
$picture = explode(' />',$array[1]);
echo '<img' . $picture[0] . ' />'; }
echo '
<style>
img {
width: 150px;
height: 100px;
float: left;
margin-right: 20px;
}</style>
';
}
function preview($content) {
$preview = explode('<!--more-->',$content);
echo '<p style="margin-right: 20px;">' . $preview[0] . '</p>';
}
include"footer.php";
?>
答案 0 :(得分:0)
我不确定这是不是你的问题,而是你的字符串:
'SELECT * FROM wp_posts WHERE post_parent="0" ORDER BY ID DESC LIMIT $start, $per_page'
...附在'
单引号中。 PHP是PHP,如果字符串包含在"
双引号中,那么这里的插值将起作用。因此,首先,请尝试使用"
s切换'
。