I want to create a function that returns all results from a mysqli query in an array.
function Get(){
// verification... verification...
$res = $this -> link -> query("SELECT " . $select . " FROM " . $from);
while ($res->fetch_assoc())
{
$row[] = $res->fetch_assoc();
}
return $row;
}
i = 0;
var_dump(Get());
the while returns only the 1,3,5,7,9 results
Can someone explain the result?
You do twice $ref->fetch_assoc();
while ($result = $res->fetch_assoc())
{
$row[] = $result;
}
You should change your code and run:
while ($result = $res->fetch_assoc())
{
$row[] = $result;
}
Explanation:
In your code in your loop you have while ($res->fetch_assoc())
what makes that 1st record is taken from your results and it's being checked if this record is in database (it there are no records fetch_assoc
return false and loop isn't executed anymore. However you don't assign this result to any variable so this result simple disappear. Then inside your loop you use $row[] = $res->fetch_assoc();
so you take the second record from database. Now the loop is being executed again. This is how this works.
The $res->fetch_assoc()
call returns a single row from the result set and increments the internal pointer of the result set by one. Since you are calling fetch_assoc
several times per Get()
call, your results are not what you expect. If you'd like to get a single row of results, call fetch_assoc
once. If you'd like to return all the rows from the result set, do something like this:
function Get(){
// verification... verification...
$res = $this -> link -> query("SELECT " . $select . " FROM " . $from);
$rows = array();
while( $row = $res->fetch_assoc() ) {
$rows[] = $row;
}
return $rows;
}
var_dump(Get());