mysqli查询仅返回第一行 [英] mysqli query only returning first row

查看:86
本文介绍了mysqli查询仅返回第一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从mysql迁移到mysqli,但在查询中从数据库返回多个行时遇到了麻烦.

I am migrating from mysql to mysqli, and I am having trouble returning more than one row from the database in a query.

$db = new mysqli($hostname, $sql_us, $sql_us_pwd, $sql_db); // This is already connected

function db_query($db, $query, $type = 'object') {

    global $db;

    $result = $db->query($query);

    if ($type == 'assoc') {
        while($row = $result->fetch_assoc()) {
          return $row;
        }
    } else {    
        while($row = $result->fetch_object()) {
          return $row;
        }   
    }

    mysqli_free_result($result);

}



$query = "SELECT * FROM `users`";
$user = db_query($db, $query);
print_r($user); // This is only returning the first row of results

很显然,我正在尝试创建一个函数,在该函数中我可以查询数据库,并以关联数组或对象的形式返回结果.我在做什么错了?

I'm obviously trying to make a function where I can query the database and either return the results in an associative array or as an object. What am I doing wrong?

推荐答案

使用以下代码:

$rows = array();
if ($type == 'assoc') {
    while($row = $result->fetch_assoc()) {
      $rows[] = $row;
    }
} else {    
    while($row = $result->fetch_object()) {
      $rows[] = $row;
    }   
}
return $rows;

您在while内使用return,并且return在第一次迭代后终止while循环,这就是为什么只获得一行的原因.

You are using the return inside the while and return terminates the while loop after first iteration that's why you are getting only one row.

这篇关于mysqli查询仅返回第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆