Bird
Raised Fist0
PHPprogramming~20 mins

Executing queries with query method in PHP - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Query Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this PHP code using query method?

Consider the following PHP code snippet that uses the query method to fetch data from a database. What will be the output?

PHP
<?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'];
?>
ASyntaxError: Unexpected token in query method
BThe name of the user with id 1 is printed
CFatal error: Call to undefined method query()
DEmpty output because query returns false
Attempts:
2 left
💡 Hint

Remember that query returns a result object on success, and you can fetch rows from it.

❓ Predict Output
intermediate
2:00remaining
What error does this PHP code raise when using query method?

Look at this PHP code snippet. What error will it produce?

PHP
<?php
$mysqli = new mysqli('localhost', 'user', 'pass', 'testdb');
$result = $mysqli->query('SELECT * FROM non_existing_table');
if (!$result) {
    echo $mysqli->error;
}
?>
AOutputs an error message about unknown table
BSyntaxError: Invalid SQL syntax
CFatal error: Call to undefined method query()
DNo output, query returns empty result
Attempts:
2 left
💡 Hint

Check what happens when the query references a table that does not exist.

🔧 Debug
advanced
2:00remaining
Why does this PHP code using query method cause a fatal error?

Examine this PHP code snippet. It causes a fatal error. What is the cause?

PHP
<?php
$mysqli = new mysqli('localhost', 'user', 'pass', 'testdb');
$result = $mysqli->query('SELECT id FROM users');
echo $result['id'];
?>
Amysqli connection failed causing fatal error
BQuery method returns false due to syntax error
Cfetch_assoc() method missing causing fatal error
DTrying to access result object as array causes fatal error
Attempts:
2 left
💡 Hint

Remember what type query returns and how to access data from it.

📝 Syntax
advanced
2:00remaining
Which option correctly uses the query method to fetch all user names?

Choose the PHP code snippet that correctly fetches and prints all user names from the database using the query method.

A
&lt;?php
$result = $mysqli-&gt;query('SELECT name FROM users');
while ($row = $result-&gt;fetch_assoc()) {
    echo $row['name'] . '\n';
}
?&gt;
B
&lt;?php
$result = $mysqli-&gt;query('SELECT name FROM users');
for ($i=0; $i &lt; count($result); $i++) {
    echo $result[$i]['name'] . '\n';
}
?&gt;
C
&lt;?php
$result = $mysqli-&gt;query('SELECT name FROM users');
foreach ($result as $row) {
    echo $row['name'] . '\n';
}
?&gt;
D
&lt;?php
$result = $mysqli-&gt;query('SELECT name FROM users');
echo $result['name'];
?&gt;
Attempts:
2 left
💡 Hint

Think about how to iterate over a mysqli result set properly.

🚀 Application
expert
2:00remaining
How many rows are returned by this PHP query method call?

Given this PHP code, how many rows will $count hold after execution?

PHP
<?php
$mysqli = new mysqli('localhost', 'user', 'pass', 'testdb');
$result = $mysqli->query('SELECT * FROM users WHERE age > 30');
$count = $result->num_rows;
?>
ATotal number of users in the database
BAlways zero because num_rows is not supported
CThe number of users with age greater than 30
DOne, because query returns only one row by default
Attempts:
2 left
💡 Hint

Check what num_rows property represents after a SELECT query.

Practice

(1/5)
1. What does the query method in PHP do when used with a database connection?
easy
A. It executes an SQL statement on the database.
B. It creates a new database connection.
C. It formats the SQL query string.
D. It closes the database connection.

Solution

  1. Step 1: Understand the purpose of the query method

    The query method is designed to send SQL commands to the database for execution.
  2. Step 2: Identify what the method does with the SQL statement

    It runs the SQL command and returns the result, such as data or success status.
  3. Final Answer:

    It executes an SQL statement on the database. -> Option A
  4. Quick Check:

    query method = executes SQL [OK]
Hint: query method runs SQL commands on the database [OK]
Common Mistakes:
  • Thinking query creates or closes connections
  • Confusing query with preparing statements
  • Assuming query formats SQL strings
2. Which of the following is the correct syntax to execute a SELECT query using the query method on a PDO object named $pdo?
easy
A. $pdo->query = 'SELECT * FROM users';
B. $pdo->execute('SELECT * FROM users');
C. query($pdo, 'SELECT * FROM users');
D. $pdo->query('SELECT * FROM users');

Solution

  1. Step 1: Recall the method call syntax for PDO query

    The query method is called on the PDO object using arrow notation with the SQL string as argument.
  2. Step 2: Check each option for correct syntax

    $pdo->query('SELECT * FROM users'); correctly calls $pdo->query('SELECT * FROM users');. Others misuse assignment, function call, or wrong method.
  3. Final Answer:

    $pdo->query('SELECT * FROM users'); -> Option D
  4. Quick Check:

    Correct method call = $pdo->query('SELECT * FROM users'); [OK]
Hint: Use arrow operator and pass SQL string to query() [OK]
Common Mistakes:
  • Using assignment instead of method call
  • Calling query as a standalone function
  • Using execute instead of query for simple queries
3. What will be the output of the following PHP code snippet?
$pdo = new PDO('sqlite::memory:');
$pdo->exec('CREATE TABLE test (id INTEGER)');
$pdo->exec('INSERT INTO test (id) VALUES (1), (2), (3)');
$result = $pdo->query('SELECT COUNT(*) FROM test');
$count = $result->fetchColumn();
echo $count;
medium
A. 3
B. COUNT(*)
C. 1
D. Error

Solution

  1. Step 1: Understand the SQL commands executed

    The code creates a table and inserts three rows with ids 1, 2, and 3.
  2. Step 2: Analyze the SELECT COUNT(*) query and fetch result

    The query counts rows in the table, which is 3. fetchColumn() returns this count as a string.
  3. Final Answer:

    3 -> Option A
  4. Quick Check:

    Row count = 3 [OK]
Hint: COUNT(*) returns number of rows, fetchColumn gets that value [OK]
Common Mistakes:
  • Confusing fetchColumn() with fetch() returning array
  • Expecting column name instead of count value
  • Assuming query returns error without table
4. Identify the error in the following PHP code that uses the query method:
$pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass');
$sql = "INSERT INTO users (name) VALUES ('Alice')";
$result = $pdo->query($sql);
if ($result) {
    echo "Insert successful";
} else {
    echo "Insert failed";
}
medium
A. PDO connection string is wrong.
B. The SQL syntax is incorrect for INSERT.
C. Using query() for INSERT may not return true/false as expected.
D. Missing fetch() after query() call.

Solution

  1. Step 1: Check usage of query() with INSERT statements

    The query method can execute INSERT but returns a PDOStatement or false, not a simple true/false.
  2. Step 2: Understand how to check success of INSERT

    For INSERT, it's better to use exec() which returns affected rows count or false on failure.
  3. Final Answer:

    Using query() for INSERT may not return true/false as expected. -> Option C
  4. Quick Check:

    query() returns PDOStatement, not boolean for INSERT [OK]
Hint: Use exec() for INSERT to get affected rows count [OK]
Common Mistakes:
  • Expecting query() to return boolean for INSERT
  • Confusing query() and exec() methods
  • Ignoring return value type of query()
5. You want to retrieve all usernames from a users table and store them in an array using the query method. Which code snippet correctly does this?
hard
A. $usernames = $pdo->query('SELECT username FROM users')->fetch(PDO::FETCH_COLUMN);
B. $stmt = $pdo->query('SELECT username FROM users'); $usernames = $stmt->fetchAll(PDO::FETCH_COLUMN);
C. $usernames = $pdo->query('SELECT username FROM users')->fetchColumn();
D. $usernames = $pdo->query('SELECT username FROM users')->fetchAll();

Solution

  1. Step 1: Understand how to fetch all values from a single column

    The fetchAll(PDO::FETCH_COLUMN) fetches all rows from the first column into an array.
  2. Step 2: Check each option for correct usage

    $stmt = $pdo->query('SELECT username FROM users'); $usernames = $stmt->fetchAll(PDO::FETCH_COLUMN); correctly calls query(), then fetchAll with FETCH_COLUMN to get usernames array. Others misuse fetchAll or fetchColumn.
  3. Final Answer:

    $stmt = $pdo->query('SELECT username FROM users'); $usernames = $stmt->fetchAll(PDO::FETCH_COLUMN); -> Option B
  4. Quick Check:

    fetchAll(PDO::FETCH_COLUMN) returns array of column values [OK]
Hint: Use fetchAll(PDO::FETCH_COLUMN) to get single column array [OK]
Common Mistakes:
  • Using fetchColumn() to get all rows instead of one
  • Not storing query result before fetching
  • Passing wrong fetch mode to fetch()
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard