我遵循了关于PHP的书中的代码,但我遇到了以下问题:它显示了我的数据库中的帖子,但是当我点击"阅读更多"链接它告诉我它无法找到URL。以下是代码
任何有关错误的建议都会非常感激。
posts.php
<?php
Class Posts {
public $db = '';
public function __construct(){
$this->db = new PDO("mysql:host=localhost;dbname=testposts", "username", "password");
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->index();
}
public function index(){
$id = 0;
$posts = array();
$template = '';
if (!empty($_GET['id'])){
$id = $_GET['id'];
}
try {
if (!empty($id)){
$query = $this->db->prepare("SELECT * FROM posts WHERE id = ?");
$params = array($id);
$template = 'single-post.php';
} else {
$query = $this->db->prepare("SELECT * FROM posts");
$params = array();
$template = 'list-posts.php';
}
$query->execute($params);
for ($i = 0; $row = $query->fetch(); $i++) {
$posts[] = array('id' => $row['id'], 'content' => $row['content']);
}
} catch (PDOException $e){
$e->getMessage();
}
$query->closeCursor();
$db = null;
require_once($template);
}
}
$posts = new Posts();
?>
列表posts.php
<h1>List of Blog Posts</h1>
<?php foreach ($posts as $post): ?>
<h3>Post # <?php echo htmlspecialchars($post['id']); ?></h3>
<?php echo htmlspecialchars($post['content']); ?>
<a href="http://localhost/other/posts.php?id=<?php
echo htmlspecialchars($post['id']); ?>">Read More</a>
<hr>
<?php endforeach; ?>
单post.php中
<?php foreach ($posts as $post): ?>
<h1>Post #<?php echo htmlspecialchars($post['id']); ?></h1>
<hr>
<?php echo htmlspecialchars($post['content']); ?>
<a href="http://localhost/other/posts.php">Back to Post List</a>
<?php endforeach; ?>