douxuanjie2692 2018-08-12 12:15
浏览 502
已采纳

如何使用mysqli_fetch_all()从查询中返回空数组或结果集?

My PHP code:

function get_something() {

  global $link;

  $sql = "SELECT * FROM new";

  $result = mysqli_query($link, $sql);

  $names = mysqli_fetch_all($result, MYSQLI_ASSOC);

  return $names;

}

What is my problem:

When my table new is empty, I get the following error:

mysqli_fetch_all() expects parameter 1 to be mysqli_result`

If it isn't empty everything is working fine.

I need to check if my database is empty and if it's not, I will call mysqli_fetch_all. Otherwise, my function should return an empty array.

How is this possible to do?

  • 写回答

2条回答 默认 最新

  • douwa6220 2018-08-12 12:17
    关注

    Use mysqli_num_rows($result) to check how many rows were returned from the query. But if table new doesn't exist, $result will be false so we have to check that $result is valid as well:

    if ($result && mysqli_num_rows($result) > 0)
        $names = mysqli_fetch_all($result, MYSQLI_ASSOC);
    else
        $names = array();
    return $names;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • dstk51319 2018-08-12 13:47
    关注

    mysqli_fetch_all($result, MYSQLI_ASSOC) generates an indexed array of associative arrays. When there are no rows found, it will deliver an empty array (which is what you want). It is absolutely pointless to call mysqli_num_rows(), so don't make your script do any unnecessary work.

    Furthermore:

    • many developers will advise you not to make global declarations to pass variables in your custom function scope. Instead, pass the connection variable into your function as a parameter.
    • I always try to avoid declaring single use variables. For your case, $sql and $names will only be used/referenced once after being declared, so just don't declare them.
    • As a matter of personal preference, I recommend using OO syntax with mysqli functions because it is less verbose, but in my following snippet I'll leave it like your original post.

    Suggested Code:

    function get_something($link) {
        if (!$result = mysqli_query($link, "SELECT * FROM new")) {
            return [];  // check mysqli_error($link) because your query failed
        }
        return mysqli_fetch_all($result, MYSQLI_ASSOC);
    }
    
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 怎么下载MySQL,怎么卸干净原来的MySQL
  • ¥15 网络打印机Ip地址自动获取出现问题
  • ¥15 求局部放电案例库,用于预测局部放电类型
  • ¥100 QT Open62541
  • ¥15 stata合并季度数据和日度数据
  • ¥15 谁能提供rabbitmq,erlang,socat压缩包,记住版本要对应
  • ¥15 Vue3 中使用 `vue-router` 只能跳转到主页面?
  • ¥15 用QT,进行QGIS二次开发,如何在添加栅格图层时,将黑白的矢量图渲染成彩色
  • ¥50 监控摄像头 乐橙和家亲版 保存sd卡的文件怎么打开?视频怎么播放?
  • ¥15 Python的Py-QT扩展库开发GUI