【发布时间】:2021-09-10 12:24:29
【问题描述】:
我有一个从 MySQL 数据库中获取记录的 PDO 语句,如果没有返回记录(即用户尚未添加任何帖子),我想在页面上回显一些文本。
我认为在 while 循环之后,我可以执行一个 if 语句来确认行的存在。这确实会回显字符串,但在显示帖子时也会回显字符串?
<?php
isset($_GET['username']) ? $username = $_GET['username'] : header("Location: login.php");
$stmt = $connection->prepare("SELECT * FROM posts WHERE username = :username");
$stmt->execute([':username' => $username]);
while ($row = $stmt->fetch()) {
$db_post_id = htmlspecialchars($row['image_id']);
$db_title = htmlspecialchars($row['image_title']);
$db_tags = htmlspecialchars($row['image_tags']);
$db_processed= htmlspecialchars($row['user_processed']);
$db_username = htmlspecialchars($row['username']);
$db_profile_image_filename = htmlspecialchars($row['profile_image']);
if ($db_processed === 'yes') {
?>
<article>
<!-- HTML goes here that includes above data from database -->
</article>
<?php }
}
if ($row == 0) {
echo "no data to show";
}
?>
【问题讨论】:
-
我相信你的情况是错误的。尝试“回显 $row;”在循环内部并在两种情况下检查其值。另一种方法是使用 rowCount(),例如:$row_count = $stmt->rowCount();并在条件下将 it 与 0 进行比较。
-
@OfirBaruch mmm...是的,当我在底部代码块中回显 $row 时,屏幕上不会打印任何内容。它在其他答案中说不要将 rowCount() 用于此类任务,因为如果您开始在表中累积大量行,它会增加对数据库的不必要需求,即它可能会对性能产生影响?
-
添加了一个答案,希望对您有所帮助:)