繁体   English   中英

遍历两个数据库表

[英]looping through two database tables

在我的数据库中,我有诸如postuserpost表。 我希望能够显示谁发布了哪些帖子。

我用下面的foreach循环。 我想要实现的是拥有另一个foreach循环,以便我可以为user循环,或者有另一种方法可以做到这一点?

post table

+--------------+--------------------+-------------------+-------------------
| post_id      | user_id            | title             | time             |
+--------------+--------------------+-------------------+-------------------
| 1            | 2                  | Good service      | 12:00PM          |
+--------------+--------------------+-------------------+-------------------
| 2            | 3                  | Thank you         | 2:46PM           |
+--------------+--------------------+-------------------+-------------------
| 3            | 1                  | Enquiry           | 11:28AM          |
+--------------+--------------------+-------------------+-------------------

user table

+--------------+--------------------+-------------------+
| user_id      | name               | email             |
+--------------+--------------------+-------------------+
| 1            | Jane               | jane@gmail.com    |
+--------------+--------------------+-------------------+
| 2            | Ben                | ben@gmail.com     |
+--------------+--------------------+-------------------+
| 3            | John               | john@gmail.com    |
+--------------+--------------------+-------------------+


$sql = "SELECT * FROM post p inner join user u ";
                    $sql .= "ON p.user_id = u.user_id ";
                    $sql .= "LIMIT {$per_page} ";
                    $sql .= "OFFSET {$pagination->offset()}";
                    $posts = post::find_by_sql($sql);

foreach ($posts as $post) {    
  echo "<div class='panel-body'>" .
  "<div class='post'>" .
  "<h3>";
  echo $post->title;
  echo "</h3>";
  echo "<p><span class='name'>" . $post->name . " - " . $post->time . "</span>";
  //the rest are the continuation of the html and php codes for looping `$post`
}

name是从user表中获取的,而其他变量是从post表中获取的。

错误: Notice: Undefined property: post::$name

尽管我在post表中没有name ,但我将两个表连接在一起了吗?

$sql = "SELECT * FROM post p inner join user u ";
  $sql .= "ON p.user_id = u.user_id ";
  $sql .= "LIMIT {$per_page} ";
  $sql .= "OFFSET {$pagination->offset()}";
  $posts = post::find_by_sql($sql);

foreach ($posts as $jp) {
  $user = User::find_by_id($jp->user_id);   //add this
  echo "<div class='panel-body'>" .
  "<div class='post'>" .
  "<h3>";
  echo $jp->title;
  echo "</h3>";
  echo "<p><span class='name'>" . $user->name . " - " . $jp->time . "</span>";
  //the rest are the continuation of the html and php codes for looping `$post`
}                      

您需要从结果集中的“ u.name”列获取值,而不是“ name”或类似名称。 这是因为您正在使用SELECT *

因此,值将在$ post ['u.name']和类似的位置。

您实际上应该远离*选择,而仅选择可能需要的列(可能包括列别名)以使结果查找更加容易。

暂无
暂无

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

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