function returns only first array value with mysql

2019-01-20 20:52发布

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!

2条回答
成全新的幸福
2楼-- · 2019-01-20 21:02

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

查看更多
叼着烟拽天下
3楼-- · 2019-01-20 21:10
$data  = array();
$query = "SELECT * FROM uploads";
if ($result = $mysqli->query($query)) {
  while ($row = $result->fetch_assoc()) {
     $data[] = $row;
  }
}
return $data;
查看更多
登录 后发表回答