PHP数组未显示在页面中
注释列表应显示在ul li范围内,是否有任何原因说明它们没有显示,而数组显示在页面顶部 数据库连接似乎工作得很好,但是注释没有显示在范围内。它还删除了“您没有添加任何注释文本” 代码PHP数组未显示在页面中,php,html,pdo,Php,Html,Pdo,注释列表应显示在ul li范围内,是否有任何原因说明它们没有显示,而数组显示在页面顶部 数据库连接似乎工作得很好,但是注释没有显示在范围内。它还删除了“您没有添加任何注释文本” 代码 请随意使用下面的示例进行查询 // Your sql query $sql = "SELECT ID, note FROM notes"; // Prepare your statement $stmt = $db -> prepare($sql); // Execute your
请随意使用下面的示例进行查询
// Your sql query
$sql = "SELECT ID, note FROM notes";
// Prepare your statement
$stmt = $db -> prepare($sql);
// Execute your prepared statement
$stmt -> execute();
// Retreive all rows
$notes = $stmt -> fetchAll();
// Check if array is not empty
if (!empty($notes)) {
//Spit out the array
print_r($notes);
}
工作代码
<?php
require_once 'app/init.php';
$notesQuery = $db->prepare("
SELECT ID, note
FROM notes
");
$notesQuery->execute();
$notes = $notesQuery->rowCount() ? $notesQuery : [];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Notes</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>myNotes</h1>
<nav>
<a href="index.php">Home</a>
<a href="about.html">About</a>
<a href="contact.html">Contact</a>
</nav>
</header>
<div class="container">
<form action="add.php" method="post">
<textarea name="note" placeholder="Insert a note..." autocomplete="off" required></textarea>
<input type="submit" value="Add" />
</form>
<div class="notes">
<h2>Notes</h2>
<?php if(!empty($notes)): ?>
<ul>
<?php foreach($notes as $note): ?>
<li>
<span><?php echo $note['note']; ?></span>
</li>
<?php endforeach; ?>
</ul>
<?php else: ?>
<p>you haven't added any notes yet.</p>
<?php endif; ?>
</div>
</div>
</body>
</html>
印制美元钞票;在foreach循环之前。对不起,我要把这个放在哪里?如果我把它放在I receive`PDOStatement Object[queryString]=>SELECT ID,note FROM notes`前面,您已经执行了该语句,但尚未获取行。$notes是什么类型的对象?这是哪个数据库访问库?我很惊讶您可以在查询上运行一个循环,而不调用另一个方法来提取结果?看起来$notes不是数组,更像是查询结果集的迭代器,如果查询返回5行,那么$notes=5,则只能使用onceNo。
<?php
require_once 'app/init.php';
$notesQuery = $db->prepare("
SELECT ID, note
FROM notes
");
$notesQuery->execute();
$notes = $notesQuery->rowCount() ? $notesQuery : [];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Notes</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>myNotes</h1>
<nav>
<a href="index.php">Home</a>
<a href="about.html">About</a>
<a href="contact.html">Contact</a>
</nav>
</header>
<div class="container">
<form action="add.php" method="post">
<textarea name="note" placeholder="Insert a note..." autocomplete="off" required></textarea>
<input type="submit" value="Add" />
</form>
<div class="notes">
<h2>Notes</h2>
<?php if(!empty($notes)): ?>
<ul>
<?php foreach($notes as $note): ?>
<li>
<span><?php echo $note['note']; ?></span>
</li>
<?php endforeach; ?>
</ul>
<?php else: ?>
<p>you haven't added any notes yet.</p>
<?php endif; ?>
</div>
</div>
</body>
</html>