我正在用PHP学习PHP用于绝对的初学者。按照第5章的教程,我遇到了一些奇怪的错误。我正在尝试输出数据库中的条目。当我加载页面时,我得到"Notice: Undefined index: title in /home/craig/public_html/PHP tutorials/simple blog/index.php on line 42"
还有:
Notice: Undefined index: entry in /home/craig/public_html/PHP tutorials/simple blog/index.php on line 43
现在,当我输出var_dump($ e)时,我得到输出:
array(1) { [0]=> array(4) { ["title"]=> string(13) "I like Cheese" [0]=> string(13) "I like Cheese" ["entry"]=> string(17) "this is some text" [1]=> string(17) "this is some text" } }
据我所知,有索引'title'和'entry',并且数据库中的信息被拉出。那么,为什么我会得到这些未定义的索引错误?
这里是index.php的代码,如果需要,我也可以粘贴functions.php,但据我所知,它可以正常工作。
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<?php
include_once 'inc/functions.inc.php';
include_once 'inc/db.inc.php';
//open a database connection
$db = new PDO(DB_INFO, DB_USER, DB_PASS);
//Determine if an entry ID was passed in the URL
$id = (isset($_GET['id'])) ? (int) $_GET['id'] : NULL;
// load the entries
$e = retrieveEntries($db, $id);
//get the fulldisp flag and remove it from the array
$fulldisp = array_pop($e);
//saniteze the entry data
$e = sanitizeData($e);
?>
<head>
<meta http-equiv="Content-Type"
content="text/html;charset=utf-8" />
<link rel="stylesheet" href="css/default.css" type="text/css" />
<title> Simple Blog </title>
</head>
<body>
<h1> Simple Blog Application </h1>
<div id="entries">
<?php
// if the full display flag is set, show the entry
if($fulldisp==1){
var_dump($e);
?>
<h2> <?php echo $e['title'] ?></h2>
<p> <?php echo $e['entry']?></p>
<p class="backlink">
<a href="./">Back to Latest Entries</a>
</p>
<?php
}//end if statement
//if the full display flag is 0, format linked entry titles
else{
//loop through each entry
foreach($e as $entry){
?>
<p> <a href="?id=<?php echo $entry['id']?>">
<?php echo $entry['title'] ?>
</a>
</p>
<?php
} //end the foreach loop
} // end the else
?>
<p class="backlink">
<a href="admin.php">Post a new Entry</a>
</p>
</div>
</body>
</html>
无论是否有一个项目要显示,或者循环需要运行以输出多个项目,我都会收到这些错误。非常感谢您的帮助!
答案 0 :(得分:0)
这是因为$ e是一个多维数组 - 它是一个数组数组。在foreach循环中,$ entry引用多维数组的每个子数组$ e。在条件语句的第一个分支中,当您真的想引用$ e中的第一个数组时,您将引用多维数组$ e。
请改为尝试:
if($fulldisp==1){
$entry=$e[0]; //$entry is now referencing the first entry in $e rather than $e itself
?>
<h2> <?php echo $entry['title'] ?></h2>
<p> <?php echo $entry['entry']?></p>
<p class="backlink">
<a href="./">Back to Latest Entries</a>
</p>
<?php
}