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);
?>
(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.0)
PDO::query — Prepara y ejecuta una consulta SQL sin marcadores de sustitución
$query
, ?int $fetchMode
= PDO::FETCH_COLUMN, int $colno
): PDOStatement|false$query
,$fetchMode
= PDO::FETCH_CLASS,$classname
,$constructorArgs
$query
, ?int $fetchMode
= PDO::FETCH_INTO, object $object
): PDOStatement|falsePDO::query() prepara y ejecuta una consulta SQL en una sola llamada de función, retornando la consulta como objeto PDOStatement.
Para una consulta que debe ejecutarse varias veces, se obtendrán mejores resultados si se prepara el objeto PDOStatement utilizando la función PDO::prepare() y se ejecuta la consulta mediante múltiples llamadas a la función PDOStatement::execute().
Si no se recuperan todos los datos del conjunto de resultados antes de ejecutar la siguiente llamada a PDO::query(), la llamada puede fallar. Llamar a PDOStatement::closeCursor() para liberar los recursos de la base de datos asociados al objeto PDOStatement antes de ejecutar la siguiente llamada a la función PDO::query().
Nota:
Si
query
contiene marcadores de sustitución, la consulta debe prepararse y ejecutarse por separado utilizando las funciones PDO::prepare() y PDOStatement::execute().
query
La consulta SQL a preparar y ejecutar.
Si el SQL contiene marcadores de sustitución, PDO::prepare() y PDOStatement::execute() deben ser utilizados en su lugar. Alternativamente, el SQL puede ser preparado manualmente antes de llamar a PDO::query(), con los datos correctamente formateados utilizando PDO::quote() si el controlador lo soporta.
fetchMode
El modo de recuperación por omisión para el
PDOStatement retornado.
Esto debe ser una de las constantes
PDO::FETCH_*
.
Si este argumento es pasado a la función, el resto de los argumentos serán tratados como si PDOStatement::setFetchMode() hubiera sido llamado sobre el objeto de la consulta resultante. Los argumentos siguientes dependen del modo de recuperación seleccionado.
Retorna un objeto PDOStatement o false
si ocurre un error.
Emite un error de nivel E_WARNING
si el atributo PDO::ATTR_ERRMODE
está definido
a PDO::ERRMODE_WARNING
.
Lanza una excepción PDOException si el atributo PDO::ATTR_ERRMODE
está definido
a PDO::ERRMODE_EXCEPTION
.
Ejemplo #1 SQL sin marcadores de sustitución puede ser ejecutado utilizando PDO::query()
<?php
$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 ejemplo anterior mostrará :
apple red 150 banana yellow 250 kiwi brown 75 lemon yellow 25 orange orange 300 pear green 150 watermelon pink 90
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);
?>
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);
?>
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;
> 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);
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");
}
?>