繁体   English   中英

PHP查询多个表

[英]PHP query multiple Tables

我无法从此查询中获取要显示的任何信息。 有谁知道我哪里出错了?

谢谢!

 $query =   "SELECT * ".
            "FROM comments, users ".
            "WHERE comments.user_id = users.user_id ".
            "ORDER BY comments.date DESC ".
            "LIMIT 10";

$result = mysql_query($query) or die(mysql_error());

   while ($row = mysql_fetch_array($result)) {


  echo $row['users.user_id'];
  echo $row['comments.comment'];


 }

使用 mysql_fetch_assoc() 而不是 mysql_fetch_array()。 在循环中使用列名作为数组键:

while ($row = mysql_fetch_assoc($result)) {

  echo $row['column_name1'];
  echo $row['column_name1'];

}

在您的查询中尽量对 select 语句更加具体,尽量不要使用 *.

您可能会收到错误消息,因为您正在对查询中不存在的字段进行排序 (ORDER BY)。

最好不要使用“SELECT *”查询。 如果您只需要特定值,请指定它们。 这也有助于检索数据...

$query =   "SELECT users.user_id, comments.comment, comments.date ".
                        "FROM comments, users ".
                        "WHERE comments.user_id = users.user_id ".
                        "ORDER BY comments.date DESC ".
                        "LIMIT 10";

$result = mysql_query($query) or die(mysql_error());

   while ($row = mysql_fetch_array($result)) {


  echo $row['user_id'];
  echo $row['comment'];
  echo $row['date'];


 }

在查询中指定列名而不是使用 * 是一种很好的做法 - 在某些 DB 上会影响性能,并且在所有情况下都可以防止因表更改而出现任何意外行为。

在示例中,我认为问题出在您使用的数组键上 - 您不需要在其中包含表名,只需包含列名:

  echo $row['user_id']; 
  echo $row['comment'];

更好的做法是在 sql 查询中只编写您需要的字段,如下所示:

$query =   "SELECT u.user_id uid, c.comment comment ".
                    "FROM comments c, users u ".
                    "WHERE comments.user_id = users.user_id ".
                    "ORDER BY comments.date DESC ".
                    "LIMIT 10";

使用此类查询可以减少执行查询和将数据从数据库服务器传输到 php 脚本的时间。 在此修改后,您的循环转换为:

while ($row = mysql_fetch_array($result)) {
 echo $row['uid'], $row['comment'];

}

我使用 PDO 方法,但这也适用于您:

<?php
  $sql = "SELECT * FROM comments as c INNER JOIN users as u ON  c.user_id=u.user_id WHERE u.user_id=:user_id ORDER BY c.date DESC LIMIT 10";
  

  //prepare the connection to database
  $prep = $conn->prepare($sql);

  //change the parameters for user_id on WHERE condition you can put anything you want but i will put the user session id
  $prep->bindParam(":user_id", $_SESSION['user_id']);
  $prep->execute();

 //ill use fetchAll function because it can be more than 1 comment
 $datas = $prep->fetchAll();

foreach($datas as $data){
  echo $data['user_id'];
  echo $data['comment'];
  echo $data['date'];
}

?>

暂无
暂无

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

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