我有一個while循環從這句話在這裏遍歷PHP一列中的所有行
$stmt = $conn->prepare("SELECT images.*, users.profile_image, comments.* FROM
images LEFT JOIN users ON images.user_id = users.user_id LEFT JOIN comments ON
comments.user_id = users.user_id AND images.id = comments.image_id WHERE
images.id = :id");
沒有問題的檢索信息,但我需要再次循環的意見,否則,第一循環,因爲註釋表中有兩行,所以再次循環。這會再次顯示所有內容,但包含評論的第2行。我怎樣才能讓它只循環評論。第一個循環只會檢索一個結果,因爲它始終是一個唯一的ID。
try {
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$stmt->bindParam(':id', $id);
$conn->beginTransaction();
$stmt->execute();
$conn->commit();
while ($row = $stmt->fetch())
{
$comment = $row['comment'];
$title = $row['title'];
$image = $row['image'];
$username = $row['username'];
$category = $row['category'];
$description = $row['description'];
$comments = array($row['comment']);
}
?>
<h1><?php echo"$title"; ?></h1>
<img style="max-width: 100%; max-height:100%; margin-left: auto; margin-
right: auto; display:block;" src="<?php echo "$image" ?>"/>
<?php
echo "<h2><span class='by'>By </span><a
href='users.php/$username.html'>$username </a></h2>";
echo "<h2><span class='by'>In the </span><a href='browse.php?
category=space'>$category </a><span class='by'>category</span></h2>";
echo "<h2><span class='by'>About this image:</span></h2>
$description";
?>
<?php
echo "<h2><span class='by'>Comments</span></h2> $comments";
?>
<?php }
else {
if(!isset($row['id'])){
echo "empty";
}
}
?>
謝謝!
更新
while ($crow = $cstmt->fetch())
{
if($crow == false){
echo "nothing here";
}
else {
$comment = $crow['comment'];
echo "$comment"; ?><br /><br /><?php
}
}
你可以運行一個新的sql來獲取後循環中的註釋。刪除帖子加評論, –
你應該試試Laravel和Eloquent,它對錶格中的關係有很大的支持。 – silkfire