使用fetch_object()显示来自MySQL的另一个相关表的行

时间:2013-12-19 18:30:30

标签: php mysql mysqli relational-database echo

尝试从另一个表中回显作者列。目前在数据库中有两个表,一个称为entries,另一个称为comments。两者都有ID但两者都具有相同的列名“author”。在SQL语句中,您将执行select * from $table1 t1, $table2 t2 where t1.blogID = t2.blogID and t1.blogID = $postID。我知道如何使用fetch_object()

从一个表中回显
if (!empty($postID)) {
$command = "select * from $table_name where blogID = $postID";
$result = $db->query($command);
while ($data = $result->fetch_object()) {
  $postID = $data->blogID;
  echo "<TR><TD>".$postID."</TD>";
  echo "<TD>".$data->author."</TD>";
  echo "<TD>".$data->date."</TD>";
  echo "<TD>".$data->entry."</TD></TR>\n";

但是,如果我希望$command在两个表上选择,我怎么回应说t1.author?这意味着我$data->t1.author?那有意义吗?或者你们建议使用我上面设置的格式?

1 个答案:

答案 0 :(得分:0)

$command="select t1.name as t1name , t2.name as t2name from t1tabla as t1 ,t2table as t2";
$result = $db->query($command);
while ($data = $result->fetch_object()) {

 echo $data->t1name .'<br>';
 echo $data->t2name.'<br>' 
}