【发布时间】:2016-11-13 23:15:08
【问题描述】:
fruitget.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ssl";
$dbh = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$sqlquery = $dbh->prepare("select id, fruitname, fruitcolor, fruitimage from fruits order by rand() limit 1");
$sqlquery->execute();
$result = $sqlquery->fetchAll();
$result = array("fruits"=>$result);
header("Content-type:application/json");
$jsonfile = json_encode($result);
echo $jsonfile;
?>
index.php
<?php
$jcontent = file_get_contents("fruitget.php");
$content = json_decode($jcontent);
?>
<div class="ad">
<h1>Fruit of the Day</h1>
<?php
foreach ($content->fruits as $fruit) {
echo '<span>' . $fruit->fruitcolor . ' ' .$fruit->fruitname . '</span>';
echo "<img src='".$fruit->fruitimage."'width='300'/>";
}
?>
请记住,我只是获取实际文件的一部分,因此上面的代码不是完整文件,但这些部分是当前问题。
我得到的错误是:
注意:试图在 C:\xampp\htdocs\Week 3\Fruit\fruitads.php 第 44 行获取非对象的属性
警告:在 C:\xampp\htdocs\Week 3\Fruit\fruitads.php 第 44 行中为 foreach() 提供的参数无效
第 44 行是
foreach ($content->fruits as $fruit) {
感谢任何帮助。谢谢。这是针对班级的,完全按照老师的描述进行复制,他们的 foreach 没有错误,但我的有。
【问题讨论】:
-
检查 $content 中的内容有这么难吗?
var_dump($content); -
它是空的。为什么它是空的?
-
试着学一点....现在显示 $jcontent 中的内容,也许你最终会自己看到曙光#