简体   繁体   English

使用PHP从2个表中选择数据

[英]Selecting data from 2 tables with PHP

I am relatively new to PHP and SQL and I am creating a simple blog tool for my own page and I'm stuck on how I can make a comment section. 我对PHP和SQL相对较新,并且正在为自己的页面创建一个简单的博客工具,而我在如何创建注释部分方面受困。 I have 2 tables general, which contains the blog post and additional information comments, which contains comments 我有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";
}

I manage to get the blogposts working but as soon as I try a second query by adding 我设法使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";
}

it all just breaks. 一切都破了。 I am not able to throw in a loop that gets all the comments for the specific post before it starts loading additional posts. 在开始加载其他帖子之前,我无法陷入一个循环,无法获取该帖子的所有评论。

How would I go on about solving this? 我将如何继续解决这个问题? I might need a little spoonfeeding with comments in any code samples, 我可能需要在任何代码示例中添加一些注释,

You can use the primary key of the post and that can be used in comments table as a foreign key so that you can easily make your query with that will show all the comments against that specific post. 您可以使用帖子的主键,并且可以在评论表中将其用作外键,这样您就可以轻松地进行查询,从而显示针对该特定帖子的所有评论。 Then the query will be like this: 然后查询将是这样的:

 $postid=$row['post_id'];

$sql2 = "SELECT * FROM comments WHERE post_id='$postid' ORDER BY post_id DESC"; $ sql2 =“选择*从注释中post_id ='$ postid'ORDER BY post_id DESC”

Changing the second query to fixed the problem. 更改第二个查询以解决问题。

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

Thanks to Jeff for providing this answer 感谢Jeff提供了此答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM