Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

php - mysqli query only returning first row

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use this code:

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...