【发布时间】:2015-07-29 16:16:25
【问题描述】:
我正在尝试从数据库中获取记录,并在单击链接时传递参数以获取所需的 url。但是当我点击链接时出现以下错误:
警告:在第 31 行的 /home/next/public_html/cms/index.php 中为 foreach() 提供的参数无效
使用的代码是:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once('includes/class-query.php');
if ( !empty ( $_GET ) ) {
if ( !empty ( $_GET['p'] ) ) {
$post = $_GET['p'];
}
if ( !empty ( $_GET['cat'] ) ) {
$cat = $_GET['cat'];
}
}
if ( empty ( $post ) && empty ( $cat ) ) {
$posts_array = $query->all_posts();
} elseif ( !empty ( $post ) ) {
$posts_array = $query->post($post);
} elseif ( !empty ( $cat ) ) {
echo 'cat';
} ?>
<html>
<head>
<title></title>
</head>
<body>
<?php foreach ( $posts_array as $post ) : ?>
<div class="post">
<h1><a href="?p=<?php echo $post->ID; ?>"><?php echo $post->post_title; ?></a></h1>
<p><?php echo $post->post_content; ?></p>
</div>
<?php endforeach; ?>
</body>
</html>
【问题讨论】:
-
您的查询失败,您需要找出原因。检查 db 和 PHP 中的错误。
-
在您的条件语句中放置回声 (
echo "failed";) 并查看其中弹出的内容。您可以使用 print_r 和/或 var_dump 以这种方式对其进行跟踪/故障排除 -
我很确定
<?php print_r($posts_array); ?>可以解决问题。可能$posts_array不是数组。 -
$posts_array = $query->post($post);看起来好像只返回一个帖子,因此尝试迭代它会导致该错误,因为它不是数组。 -
返回数组