mysqli query only returning first row

2019-01-20 16:58发布

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?

标签: php mysql mysqli
5条回答
够拽才男人
2楼-- · 2019-01-20 17:35

You need to store while loop values into array try this

$rows = array();
if ($type == 'assoc') {
    while($row = $result->fetch_assoc()) {
      $rows[] = $row;
    }
} else {    
    while($row = $result->fetch_object()) {
      $rows[] = $row;
    }   
}
return $rows;
查看更多
Ridiculous、
3楼-- · 2019-01-20 17:36

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.

查看更多
叛逆
4楼-- · 2019-01-20 17:54
$arr = array();
if ($type == 'assoc') {
  while($row = $result->fetch_assoc()) {
    $arr[] = $row;
  }
}
else {    
  while($row = $result->fetch_object()) {
    $arr[] = $row;   
  }
}
return $arr;
查看更多
地球回转人心会变
5楼-- · 2019-01-20 17:58

When you return in a function it stops executing at that point and goes back to the where it was called from with the value that you are returning.

In your case when you do a return $row, you are getting out of the function as soon as the first row is read.

Fix is:

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

} else {    

    while($row = $result->fetch_object()) {
      $result[] = $row;
    }   
}
return $row;
查看更多
\"骚年 ilove
6楼-- · 2019-01-20 17:58

You are only returning the first row. You have to return an array.

查看更多
登录 后发表回答