Php得到评论

时间:2017-01-05 13:22:48

标签: php mysql

您好我试图从相关表中获得评论'评论'我的数据库。我想显示如果没有评论的消息如下:'没有结果',否则如果有评论显示评论框的用户名日期和评论的消息我试过但没有结果:

function getComments($conn) {
$sql = ("SELECT * FROM comments ORDER BY cid DESC LIMIT 5");
$result = $conn->query($sql);
foreach($row as $result) {
    if(!mysql_num_rows($sql))
{
echo 'No results';
}
else
{
echo "<div class='comment-box2'><p>";
        echo $row['users']."<br>";
        echo $row['date']."<br>";
        echo nl2br($row['message']);
    echo "</p>
    </div>";
}
}
}

1 个答案:

答案 0 :(得分:0)

我认为您没有正确订购代码,还有其他一些错误,例如混合mysqlmysqli。 (你可以看到this question来解释两者之间的区别。)试试这个:

function getComments($conn) 
{ 
  $sql = ("SELECT * FROM comments ORDER BY cid DESC LIMIT 5"); 
  $result = $conn->query($sql);

  //This line should come next;
  //you check the number of rows in the result of the query returned,
  //not in the SQL statement
  if(!($result->num_rows)) { //looks like you're using MySQLi, so you should do things properly
  echo 'No results'; 
  } else {

  //Then iterate over the rows if there were any
  while($row = $result->fetch_assoc()) { //again, using MySQLi
    echo "<div class='comment-box2'><p>"; 
    echo $row['users']."<br>"; //I'm pretty sure this should be singular
    echo $row['date']."<br>"; 
    echo nl2br($row['message']);
    echo "</p> </div>"; 
    } 
  } 
}