Getting the Result of an SQL Query in PHP
In the previous lesson, we created a test code. Let me remind you of its essential part that executes a query to the database:
<?php
$query = 'SELECT * FROM users';
$res = mysqli_query($link, $query) or die(mysqli_error($link));
var_dump($res);
?>
As you can see, after the query to the database is executed,
the variable $res
will contain the result of this action. However,
it is not in the form we need in PHP, but in the form
in which it was sent to us by the database.
To get the result in the form we are used to,
it is necessary to use the function
mysqli_fetch_assoc, which extracts one row
from the result.
Let's try:
<?php
$row = mysqli_fetch_assoc($res);
var_dump($row);
?>
As a result, var_dump will output an array
with the first employee:
<?php
['id' => 1, 'name' => 'user1', 'age' => 23, 'salary' => 400]
?>
At the same time, the first employee will disappear from the variable $res,
and the next call to mysqli_fetch_assoc
will get the next employee.
And so you can call our function until
the employees run out. As
soon as this happens, the next function call
will return false.
Let's try:
<?php
$row1 = mysqli_fetch_assoc($res);
var_dump($row1); // employee number 1
$row2 = mysqli_fetch_assoc($res);
var_dump($row2); // employee number 2
$row3 = mysqli_fetch_assoc($res);
var_dump($row3); // employee number 3
$row4 = mysqli_fetch_assoc($res);
var_dump($row4); // employee number 4
$row5 = mysqli_fetch_assoc($res);
var_dump($row5); // employee number 5
$row6 = mysqli_fetch_assoc($res);
var_dump($row6); // employee number 6
$row7 = mysqli_fetch_assoc($res);
var_dump($row7); // will output NULL - employees are finished
?>