Using PDO::query to Execute SQL and Return a PDOStatement in PHP
This article explains how the PDO::query method in PHP executes an SQL statement, returns the result as a PDOStatement object, details its parameters and return values, and provides a practical code example for retrieving and printing query results.
PDO::query is a method in PHP's PDO class that executes an SQL statement and returns the result set as a PDOStatement object.
Signature:
public PDOStatement PDO::query(string $statement, int $fetch_mode = PDO::FETCH_CLASS, string $classname, array $ctorargs)Parameters:
$statement – The SQL query to prepare and execute.
Return value: Returns a PDOStatement object on success or FALSE on failure.
Example:
<?php
function getFruit($conn) {
$sql = 'SELECT name, color, calories FROM fruit ORDER BY name';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
print $row['color'] . "\t";
print $row['calories'] . "
";
}
}
?>Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
