Consider the following PHP code snippet that uses the query method to fetch data from a database. What will be the output?
<?php $mysqli = new mysqli('localhost', 'user', 'pass', 'testdb'); $result = $mysqli->query('SELECT name FROM users WHERE id = 1'); $row = $result->fetch_assoc(); echo $row['name']; ?>
Remember that query returns a result object on success, and you can fetch rows from it.
The query method executes the SQL and returns a result object. Using fetch_assoc() retrieves the row as an associative array. Then echo prints the 'name' field.
Look at this PHP code snippet. What error will it produce?
<?php $mysqli = new mysqli('localhost', 'user', 'pass', 'testdb'); $result = $mysqli->query('SELECT * FROM non_existing_table'); if (!$result) { echo $mysqli->error; } ?>
Check what happens when the query references a table that does not exist.
The query method returns false on failure. The error message from $mysqli->error explains the problem, such as unknown table.
Examine this PHP code snippet. It causes a fatal error. What is the cause?
<?php $mysqli = new mysqli('localhost', 'user', 'pass', 'testdb'); $result = $mysqli->query('SELECT id FROM users'); echo $result['id']; ?>
Remember what type query returns and how to access data from it.
The query method returns a result object, not an array. Accessing it like an array causes a fatal error. You must fetch rows first.
Choose the PHP code snippet that correctly fetches and prints all user names from the database using the query method.
Think about how to iterate over a mysqli result set properly.
The query method returns a result object. You must use fetch_assoc() in a loop to get each row. Options A, C, and D misuse the result object.
Given this PHP code, how many rows will $count hold after execution?
<?php $mysqli = new mysqli('localhost', 'user', 'pass', 'testdb'); $result = $mysqli->query('SELECT * FROM users WHERE age > 30'); $count = $result->num_rows; ?>
Check what num_rows property represents after a SELECT query.
The num_rows property gives the number of rows in the result set. Here it counts users older than 30.