CakeFest 2024: The Official CakePHP Conference

PDO::query

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.0)

PDO::query Ejecuta una sentencia SQL, devolviendo un conjunto de resultados como un objeto PDOStatement

Descripción

public PDO::query(string $statement): PDOStatement
public PDO::query(string $statement, int $PDO::FETCH_COLUMN, int $colno): PDOStatement
public PDO::query(
    string $statement,
    int $PDO::FETCH_CLASS,
    string $classname,
    array $ctorargs
): PDOStatement
public PDO::query(string $statement, int $PDO::FETCH_INTO, object $object): PDOStatement

PDO::query() ejecuta una sentencia SQL en una única llamada a función, devolviendo el conjunto de resultados (si los hay) que devuelve la sentencia como un objeto PDOStatement.

Para una consulta que se necesite ejecutar en múltiples ocasiones, se obtendrá una mejor rendimiento si se prepara un objeto PDOStatement usando PDO::prepare() y ejecutando la sentencia con múltiple llamadas a PDOStatement::execute().

Si no se buscan todos los datos del conjunto de resultados antes de ejecutar la siguiente llamada a PDO::query(), ésta puede fallar. Llamando a PDOStatement::closeCursor() se liberan los recursos de la base de datos asociados al objeto PDOStatement antes de ejecutar la siguiente llamada a PDO::query().

Nota:

Aunque esta función está documentada solamente teniendo un único parámetro, se pueden pasar argumentos adicionales a esta función. Éstos serán tratados como si se llamase a PDOStatement::setFetchMode() con el objeto de la sentencia resultante.

Parámetros

statement

La sentencia SQL a preparar y ejecutar.

Los datos dentro de la consulta deben ser debidamente escapados.

Valores devueltos

PDO::query() devuelve un objeto PDOStatement, o false en caso de error.

Ejemplos

Ejemplo #1 Demostración de PDO::query

Una buena característica de PDO::query() es que permite iterar sobre el conjunto de filas devueltos por una ejecución de una sentencia SELECT con éxito.

<?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'] . "\n";
}
}
?>

El resultado del ejemplo sería:

apple   red     150
banana  yellow  250
kiwi    brown   75
lemon   yellow  25
orange  orange  300
pear    green   150
watermelon      pink    90

Ver también

add a note

User Contributed Notes 6 notes

up
42
fredrik at NOSPAM dot rambris dot com
16 years ago
The handling of errors by this function is controlled by the attribute PDO::ATTR_ERRMODE.

Use the following to make it throw an exception:
<?php
$dbh
->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
up
2
Ilyas Bakirov
2 years ago
I would like to mention fetching rows from SQL query using PDO:

<?php

$dbh
= new PDO('mysql:host=localhost;dbname=test', $user, $pass);

// use the connection here
$sth = $dbh->query('SELECT * FROM countries');

// fetch all rows into array, by default PDO::FETCH_BOTH is used
$rows = $stm->fetchAll();

// iterate over array by index and by name
foreach($rows as $row) {

printf("$row[0] $row[1] $row[2]\n");
printf("$row['id'] $row['name'] $row['population']\n");

}
?>
up
3
stefano[dot]bertoli [at] gmail[dot]com
9 years ago
Trying to pass like second argument PDO::FETCH_ASSOC it still work.

So passing FETCH TYPE like argument seems work.

This save you from something like:

<?php
$result
= $stmt->setFetchMode(PDO::FETCH_NUM);
?>

Example:
<?php
$res
= $db->query('SELECT * FROM `mytable` WHERE true', PDO::FETCH_ASSOC);

?>
up
1
JJimenez
5 months ago
When you make a wraper for PDO:query, you must define the method like this:

public function query( string $sql, ?int $fetchMode = null, mixed ...$fetchModeArgs) : \PDOStatement|false

if you delete one of the parameters or use one of the oficials parameters you get a Fatal error
up
1
dozoyousan at gmail dot com
17 years ago
> When query() fails, the boolean false is returned.

I think that is "Silent Mode".
If that set attribute ErrorMode "Exception Mode"
then that throw PDOException.
$pdoObj = new PDO( $dsn, $user, $pass );
$pdoObj->setAttribute("PDO::ATTR_ERRMODE", PDO::ERRMODE_EXCEPTION);
up
-1
marcos at marcosregis dot com
15 years ago
After a lot of hours working with DataLink on Oracle->MySQL and PDO we (me and Adriano Rodrigues, that solve it) discover that PDO (and oci too) need the attribute AUTOCOMMIT set to FALSE to work correctly with.
There's 3 ways to set autocommit to false: On constructor, setting the atribute after construct and before query data or initiating a Transaction (that turns off autocommit mode)

The examples:
<?php
// First way - On PDO Constructor
$options = array(PDO::ATTR_AUTOCOMMIT=>FALSE);

$pdo = new PDO($dsn,$user,$pass,$options);

// now we are ready to query DataLinks

?>

<?php
// Second Way - Before create statements
$pdo = new PDO($dsn,$user,$pass);

$pdo->setAttribute(PDO::ATTR_AUTOCOMMIT,FALSE);
// or
$pdo->beginTransaction();

// now we are ready to query DataLinks
?>

To use DataLinks on oci just use OCI_DEFAULT on oci_execute() function;
To Top