mysqli查询只返回第一行

2021-12-25 00:00:00 php mysql 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.

相关文章