get array of rows with mysqli result

2019-01-07 18:51发布

问题:

I'm trying to check if a string match one of the fields in a certain column in a table. For this, I need to get all the rows from result object. I’m using php 5.2.x so can't use fetch_row_all method; instead, I’m trying to build a new array that will hold all rows.

Here is my code:

$sql = new mysqli($config['host'],$config['user'],$config['pass'],$config['db_name']);
        if (mysqli_connect_errno())
        {
            printf("Connect failed: %s\n", mysqli_connect_error());
            exit();
        }
        $query = "SELECT domain FROM services";
        $result = $sql->query($query);           
        while($row = $result->fetch_row());
        {
            $rows[]=$row;
        }
        $result->close();
        $sql->close();
        return $rows;

$rows is supposed to be the new array that contains all, rows but instead I get an empty array.

Any ideas why this is happening?

回答1:

You had a slight syntax problem, namely an errant semi-colon.

while($row = $result->fetch_row());

Notice the semi-colon at the end? It means the block following wasn't executed in a loop. Get rid of that and it should work.

Also, you may want to check that the query actually works:

$sql = new mysqli($config['host'], $config['user'], $config['pass'], $config['db_name']);
if (mysqli_connect_errno()) {
  printf("Connect failed: %s\n", mysqli_connect_error());
  exit;
}
$query = "SELECT domain FROM services";
$result = $sql->query($query);     
if (!$result) {
  printf("Query failed: %s\n", $mysqli->error);
  exit;
}      
while($row = $result->fetch_row()) {
  $rows[]=$row;
}
$result->close();
$sql->close();
return $rows;


标签: php mysqli