簡體   English   中英

使用PHP從2個表中選擇數據

[英]Selecting data from 2 tables with PHP

我對PHP和SQL相對較新,並且正在為自己的頁面創建一個簡單的博客工具,而我在如何創建注釋部分方面受困。 我有2個常規表,其中包含博客文章和其他信息注釋,其中包含注釋

$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "blog";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error){
    die ("connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM general WHERE hidden = 'false' ORDER BY id DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0){
   while ($row = $result->fetch_assoc()){
     echo "<div class='blogpost'>
          <div class='blogbody'></div>";

     //I need to do a query into the comments table at this point to find
     //all comments matching the criteria to be matched with the post here.
     echo "<div class='comments'></div></div>";
   }
}
else{
    echo "no posts";
}

我設法使Blogpost正常工作,但是一旦我嘗試通過添加

$conn2 = new mysqli($servername, $username, $password, $dbname);
if ($conn2->connect_error){
    die ("connection failed: " . $conn2->connect_error);
}
$sql2 = "SELECT * FROM comments WHERE $row["parent"] ORDER BY id DESC";
$result2 = $conn2->query($sql2);
if ($result2->num_rows > 0){
    while ($row2 = $result2->fetch_assoc()){

    }
}
else{
    echo "no comments";
}

一切都破了。 在開始加載其他帖子之前,我無法陷入一個循環,無法獲取該帖子的所有評論。

我將如何繼續解決這個問題? 我可能需要在任何代碼示例中添加一些注釋,

您可以使用帖子的主鍵,並且可以在評論表中將其用作外鍵,這樣您就可以輕松地進行查詢,從而顯示針對該特定帖子的所有評論。 然后查詢將是這樣的:

 $postid=$row['post_id'];

$ sql2 =“選擇*從注釋中post_id ='$ postid'ORDER BY post_id DESC”

更改第二個查詢以解決問題。

WHERE $row["parent"] ORDER. Change that to WHERE parent={$row['parent']} ORDER

感謝Jeff提供了此答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM