douxuanjie2692 2018-08-12 04: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 04: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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部