好吧所以我从头开始创建了一个博客,错误地开始用mysql_语句编写它,所以我回去用PDO语句重写它。我现在遇到了从我的数据库显示我的博客文章的问题。
<?php
include 'includes.php';
echo '<h3>-----------------------------------------------------</h3>';
$blogIndex = 'SELECT * FROM blog_post ORDER BY date_posted DESC';
$blogIndexstmt = $DBH->prepare($blogIndex);
$blogIndexRows = $blogIndexstmt->fetchAll();
if(!$blogIndexRows) {
echo 'No Post Yet.';
}
else {
while($blogIndexRows->nextRowset()) {
echo '<h2>' . $row['title'] . '</h2>';
$datePosted = $row['date_posted'];
echo '<p>' . gmdate('F j, Y, g:i a', $datePosted) . '</p>';
$body = substr($row['post'], 0, 300);
echo nl2br($body) . '...<br/>';
echo '<a href="post_view.php?id=' . $row['id']. '">Read More</a> | ';
echo '<a href="post_view.php?id=' . $row['id'] . '#comments">' .
$row['num_comments'] . ' comments</a>';
echo '<hr/>';
}
}
$DBH = null;
echo <<<HTML
<a href="post_add.php">+ New Post</a>
HTML;
?>
它不显示任何内容,甚至不显示错误代码。我能够使用mysql_语句正确地完成它,但我真的想学习如何正确地做到这一点。我正在寻找正确方向的推动,你现在必须为我编码。感谢您提前帮助!
答案 0 :(得分:0)
让我们从头开始。
如果您没有传递任何参数,则不使用预准备语句。
这是什么意思?只需发出PDO的query
功能即可。
就像这样:
$query = $DBH->query('SELECT * FROM blog_post ORDER BY date_posted DESC');
如果出现问题,$ DBH-&gt;查询将在成功时返回FALSE或PDOStatement。所以下一行是检查它是否为假:
if($query === false)
{
echo $DBH->errorCode();
}
else
{
// Everything went fine, let's fetch results
$results = $query->fetchAll(PDO::FETCH_ASSOC);
// If there are any records returned, our array won't be empty.
if(count($results))
{
// $results contains all of your records. You can now loop it with for, foreach and you don't need a while loop anymore
foreach($results as $row)
{
print_r($row);
}
}
else
{
echo "There are no records in the database table :(";
}
}