0
0
PHPprogramming~10 mins

Executing queries with query method in PHP - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Executing queries with query method
Create DB connection
Prepare SQL query string
Call query() method on connection
Check if query succeeded
Fetch results
Use or display results
Close connection
This flow shows how to run a SQL query using the query() method on a database connection, check success, then fetch or handle errors.
Execution Sample
PHP
<?php
$conn = new mysqli('localhost', 'user', 'pass', 'db');
$result = $conn->query('SELECT * FROM users');
if ($result) {
  while ($row = $result->fetch_assoc()) {
    echo $row['name'];
  }
}
$conn->close();
?>
This code connects to a MySQL database, runs a SELECT query using query(), then prints each user's name.
Execution Table
StepActionEvaluationResult
1Create mysqli connectionConnection establishedConnection object created
2Call query() with 'SELECT * FROM users'Query sent to DBResult object returned
3Check if result is truthyResult is validEnter fetch loop
4Fetch first row with fetch_assoc()Row data: ['name' => 'Alice']Row array returned
5Echo $row['name']Output 'Alice'Printed 'Alice'
6Fetch second rowRow data: ['name' => 'Bob']Row array returned
7Echo $row['name']Output 'Bob'Printed 'Bob'
8Fetch next rowNo more rowsfetch_assoc() returns null
9Exit loopNo more rowsStop fetching
10Close connectionConnection closedResources freed
💡 fetch_assoc() returns null when no more rows, ending the loop
Variable Tracker
VariableStartAfter Step 2After Step 4After Step 6After Step 8Final
$connnullmysqli connection objectmysqli connection objectmysqli connection objectmysqli connection objectclosed
$resultnullmysqli_result objectmysqli_result objectmysqli_result objectmysqli_result objectmysqli_result object
$rownullnull['name' => 'Alice']['name' => 'Bob']nullnull
Key Moments - 3 Insights
Why do we check if $result is truthy before fetching rows?
Because query() returns false if the query fails. Checking $result ensures we only fetch rows if the query succeeded (see step 3 in execution_table).
What happens when fetch_assoc() returns null?
It means there are no more rows to fetch, so the loop ends (see step 8 and 9 in execution_table).
Why do we close the connection at the end?
Closing frees resources and ends the connection cleanly (step 10).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of $row after step 6?
A['name' => 'Bob']
B['name' => 'Alice']
Cnull
Dmysqli_result object
💡 Hint
Check the variable_tracker row for $row at After Step 6
At which step does the fetch loop end because there are no more rows?
AStep 7
BStep 9
CStep 8
DStep 10
💡 Hint
Look at execution_table rows where fetch_assoc() returns null
If the query failed, what would $result be after step 2?
Anull
Bfalse
Cmysqli_result object
Dempty array
💡 Hint
Recall that query() returns false on failure (see key_moments about checking $result)
Concept Snapshot
Use $conn->query($sql) to run SQL queries.
Check if result is truthy before fetching.
Use fetch_assoc() to get rows one by one.
fetch_assoc() returns null when done.
Close connection when finished.
Full Transcript
This example shows how to execute SQL queries in PHP using the query() method of a mysqli connection. First, a connection is created. Then, the query() method sends the SQL string to the database. If the query succeeds, it returns a result object. We check if the result is valid before fetching rows. Using fetch_assoc(), we get each row as an associative array until no rows remain. Each row's data can be used or printed. Finally, the connection is closed to free resources.