Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...