Mysql语句显示表或消息


mysql statement to show either table or message

我的数据库中有一个订单表,一旦用户登录到他的帐户,他/她可以查看他/她以前的订单。

我有下面的代码:

    <?php
$result = mysql_query("SELECT * FROM `order` WHERE username = '". $_SESSION['username']."' ")
or die(mysql_error()); ;
echo "<table border='0'><table border width=100%><tr><th>Product</th><th>Quantity</th><th>Price</th><th>Date</th>";
while($info = mysql_fetch_array($result))
{
        echo "<tr>";
        echo "<td>" . $info['name']. "</td>";
        echo "<td>" . $info['quantity']. "</td>";
        echo "<td>" . $info['price']. "</td>";
        echo "<td>" . $info['date']. "</td>";
}
echo "</tr>";
echo "</table>";
?>

我用什么mysql语句来显示"你还没有订购任何东西"而不是一个空白表?

谢谢

使用mysql_num_rows

<?php
$result = mysql_query("SELECT * FROM `order` WHERE username = '". $_SESSION['username']."' ")
or die(mysql_error()); ;
    if (mysql_num_rows($result) == 0) {
       echo 'you have not ordered anything yet';
    } else {
    echo "<table border='0'><table border width=100%><tr><th>Product</th><th>Quantity</th><th>Price</th><th>Date</th>";
    while($info = mysql_fetch_array($result))
    {
            echo "<tr>";
            echo "<td>" . $info['name']. "</td>";
            echo "<td>" . $info['quantity']. "</td>";
            echo "<td>" . $info['price']. "</td>";
            echo "<td>" . $info['date']. "</td>";
    }
    echo "</tr>";
    echo "</table>";
    }

您可以使用mysql_num_rows()来获取结果集中的行数。

$rows = mysql_num_rows($result);
if($rows == 0) {
   echo 'you have not ordered anything yet';
}

您可以使用mysql_num_rows():

计算语句中的结果个数
if (mysql_num_rows($result) == 0) {
  echo '<p>You have not ordered anything yet.</p>';
}
else {
  echo "<table...";
}

此外,您可能希望将while循环中的第二行移动到最后一行(echo "</tr>";),以便正确输出HTML。