循环遍历两个数据库表

时间:2015-07-29 02:30:26

标签: php mysql

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

我使用了以下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

虽然name表中没有post,但我已将这两张表连在一起了?

2 个答案:

答案 0 :(得分:2)

$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`
}                      

答案 1 :(得分:-2)

您需要从&#39; u.name&#39;中获取价值。结果集中的列不是来自&#39; name&#39;和类似的。这是因为您使用的是SELECT *

因此价值将在$ post [&#39; u.name&#39;]及类似内容。

你真的应该离开*选择并只选择你需要的列,包括列别名,以便更容易进行结果查找。