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.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using PDO::query to Execute SQL and Return a PDOStatement in PHP

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'] . "
";
    }
}
?>
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.