The $result variable contains the result set. It’s a mysqli_result object.
To iterate through all the rows in this result set you need to use a mysqli_fetch_* function, like mysqli_fetch_assoc() used in the example.
These functions get the current row from the result set and return it as a standard PHP array or object.
In the example, mysqli_fetch_assoc() returns an associative array where the array key is the name of the column (name and price) and the values are the column values.
After each iteration, the result set internal pointer moves on by 1 row so that the next time mysqli_fetch_assoc() will read the next row, until no more rows are left.
This is what happens inside the while loop in the above example:
mysqli_fetch_assoc() reads the first row from $result and returns an associative array inside $row
- The echo command prints: “Product name: Toothpaste, price: 5”
- At the next while iteration, the next row is read and the echo command prints: “Product name: Shoes, price: 50”
- When there are no more rows, mysqli_fetch_assoc() returns false and the while loop stops
If the query doesn’t return any row, the while loop does not run even once.
Now, let’s see another example.
Suppose you want to look up a specific product price from the table.
Instead of reading all the rows and looking for your product using PHP code, you can filter the SQL result directly from the database using a WHERE clause.
For example, if you want to limit the result to the rows where the product name is “Laptop”, you can use this query: