php - 确定是否返回任何内容.. PHP MySQL

标签 php html mysql html-table

我有以下代码:

<table>
<thead>
  <tr>
    <th>Service</th>
    <th>Status</th>
  </tr>
</thead>
<?php $result = mysql_query("SELECT Service, Status FROM services WHERE Company='Company 1'");
  while ($row = mysql_fetch_array($result)) {
          //  ^ must be a single '=' !!!!
      echo '<tr><td>' . $row["Service"] . '</td>';
      echo '<td>' . $row["Status"] . '</td></tr>';
  } ?>
</table>

在 HTML 表中显示来自 MySQL 数据库的多行。我的问题是..我如何确定是否没有符合我的条件的行,并显示一条消息表明它是空的?

最佳答案

在我看来,最好的方法是 if 语句 + do/while 循环:

$result = mysql_query("your query");

if ($row = mysql_fetch_array($result)) {
    do {
        // your loop stuff
    } while ($row = mysql_fetch_array($result));
} else {
    echo "No result";
}

您也可以使用 mysql_num_rows 函数,但请记住,PDO API 没有这样的函数,do/while 解决方案适用于任何 API。

附言如果您只使用数组的关联部分,请使用 mysql_fetch_assoc 而不是 mysql_fetch_array。

关于php - 确定是否返回任何内容.. PHP MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4061392/

相关文章:

php - 如何在 YII2 模型上手动更改主键

php - 在函数之间传递数据库连接

php - Symfony2 表单错误

mysql - mysql 5.5.46和5.6.28中datetime类型的区别

运行 python 应用程序时 MySql 访问被拒绝 [Ubuntu 1604/NGINX/uWSGI]

php - 新闻 系统问题(PHP 和 Mysql)

html - 在 div 上设置背景颜色( Bootstrap )

html - 单独回车的 CSS 空白预包装规则

html - 在 As3 中使用 PayPal for flash builder 4.5

mysql - 如果用户在向表中添加数据时将所有字段留空,则向用户发送消息;并且不添加数据