MySQLi only showing one result

2019-08-15 00:33发布

问题:

I have a simple problem, that my MySQLi function only shows one row / result in var_dump:

$sql       = $db->query('SELECT * FROM '.$db_prefix.'_posts');
$row       = $sql->fetch_array();

var_dump($row);

That's it. The query in phpMyAdmin shows 3 results. This one only 1. It also doesn't work with fetch_assoc() or fetch_array().

Edit: Also, I want to have the keys of the table being listed as with "fetch_array()".

回答1:

Try a while loop:

while($row = $sql->fetch_row())
{
   var_dump($row);
}

Because fetch_row(), fetch_array(), fetch_assoc() will all return one row every singe time it's being called untill it is 'out of rows'.



回答2:

You would have to iterate your results. You can always use something like this:

$sql = 'SELECT * FROM '.$db_prefix.'_posts'; 

    if ($result = $mysqli->query($sql)) { 
        while($obj = $result->fetch_object()){ 
            var_dump($obj);
        } 
    }

However this would output a lot of data (because of the var_dump). For a clean output you could use

$sql = 'SELECT * FROM '.$db_prefix.'_posts'; 

    if ($result = $mysqli->query($sql)) { 
        while($obj = $result->fetch_object()){ 
            echo $obj->*sql_columnname_here*; // Repeat for all columns

        } 
    }

fetch_row() will only contain 1 row at a time



回答3:

Try this:

$sql = $db->query('SELECT * FROM '.$db_prefix.'_posts');
$rows= $sql->fetch_row();

while ($row = $rows->fetch_row()) {
  echo $row[0]." ".$row[1];
}


标签: php mysql mysqli