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

查看:78
本文介绍了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天全站免登陆