function returns only first array value with mysql

2019-01-20 20:39发布

问题:

I have a small problem with my mysqli related function. Here is the code:

$query = "SELECT * FROM uploads";
 if ($result = $mysqli->query($query)) {
   while ($row = $result->fetch_assoc()) {
     return $row;
  }

The problem is that when I use this function $row appears to be an array, but with only the first value from the query result in it. But if I try to return var_dump($row) instead, function displays array as expected, with all the values from the query result. Can you please explain why is this happening and how to return an array with complete query result correctly. Thanks!

回答1:

$data  = array();
$query = "SELECT * FROM uploads";
if ($result = $mysqli->query($query)) {
  while ($row = $result->fetch_assoc()) {
     $data[] = $row;
  }
}
return $data;


回答2:

Change this:

while ($row = $result->fetch_assoc()) {
 return $row;
}

For:

function test(){
 $query = "SELECT * FROM uploads";
 if ($result = $mysqli->query($query)) {
  while ($row = $result->fetch_assoc()) {
 $data[]=$row;
  }
}else{
 $data=array();
}
 return $data;
}

Call test function

$bbb=test();

foreach($bbb as $key){
   $dbTableColumn1 = $key['column1'];
   $dbTableColumn2 = $key['column2'];
   $dbTableColumn3 = $key['column3'];
   //...$variable = $key['ColumnOfYourTable'];
   $text .= $dbTableColumn1.'|'.$dbTableColumn2.'|'.$dbTableColumn3.'<br/>';
  //Whatever you want to output
}

The function is only for make more readable