PDO::setAttribute

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

PDO::setAttribute Configura un atributo PDO

Descripción

public PDO::setAttribute(int $attribute, mixed $value): bool

Configura un atributo del gestor de base de datos. Algunos de los atributos genéricos se listan a continuación; algunos controladores disponen de configuraciones adicionales. Cabe señalar que los atributos específicos de un controlador no deben ser utilizados con otros controladores.

PDO::ATTR_CASE

Fuerza los nombres de columnas a una casilla particular. Puede tomar una de las siguientes valores:

PDO::CASE_LOWER
Fuerza los nombres de columnas en minúsculas.
PDO::CASE_NATURAL
Deja los nombres de columnas tal como son devueltos por el controlador de base de datos.
PDO::CASE_UPPER
Fuerza los nombres de columnas en mayúsculas.
PDO::ATTR_ERRMODE

El modo para reportar los errores de PDO. Puede tomar una de las siguientes valores:

PDO::ERRMODE_SILENT
Define solo los códigos de error.
PDO::ERRMODE_WARNING
Emite diagnósticos E_WARNING.
PDO::ERRMODE_EXCEPTION
Lanza excepciones PDOException.
PDO::ATTR_ORACLE_NULLS

Nota: Este atributo está disponible con todos los controladores, no solo Oracle.

Determina si y cómo null y las cadenas vacías deben ser convertidas. Puede tomar una de las siguientes valores:

PDO::NULL_NATURAL
No se realiza ninguna conversión.
PDO::NULL_EMPTY_STRING
Las cadenas vacías son convertidas en null.
PDO::NULL_TO_STRING
null es convertido en cadena vacía.
PDO::ATTR_STRINGIFY_FETCHES

Controla si los valores recuperados (excepto null) son convertidos en strings. Acepta un valor de tipo bool: true para activar y false para desactivar (valor por omisión). Los valores null permanecen inalterados, excepto si PDO::ATTR_ORACLE_NULLS está definido en PDO::NULL_TO_STRING.

PDO::ATTR_STATEMENT_CLASS

Configura la clase de resultado derivada de PDOStatement y definida por el usuario. Requiere array(string classname, array(mixed constructor_args)).

Precaución

No puede ser utilizado con las instancias persistentes de PDO.

PDO::ATTR_TIMEOUT

Especifica la duración del tiempo límite en segundos. Toma un valor de tipo int.

Nota:

No todos los controladores soportan esta opción, y su significado puede diferir en función de los controladores. Por ejemplo, SQLite esperará durante este período para obtener un bloqueo de escritura, pero otros controladores pueden interpretar esto como un tiempo límite de conexión o de lectura.

PDO::ATTR_AUTOCOMMIT

Nota: Disponible únicamente para los controladores OCI, Firebird y MySQL.

Determina si cada consulta es autocommit. Toma un valor de tipo bool: true para activar y false para desactivar. Por omisión, true.

PDO::ATTR_EMULATE_PREPARES

Nota: Disponible únicamente para los controladores OCI, Firebird y MySQL.

Configura la activación o desactivación de las consultas preparadas emuladas. Algunos controladores no soportan las consultas preparadas nativamente o tienen un soporte limitado. Si se define en true PDO siempre emulará las consultas preparadas, de lo contrario PDO intentará utilizar las consultas preparadas nativas. En el caso de que el controlador no pueda preparar la consulta actual, PDO siempre recaerá en la emulación de consultas preparadas.

PDO::MYSQL_ATTR_USE_BUFFERED_QUERY

Nota: Disponible únicamente para el controlador MySQL.

Configura el uso de consultas con búfer. Toma un valor de tipo bool: true para activar y false para desactivar. Por omisión, true.

PDO::ATTR_DEFAULT_FETCH_MODE

Define el modo de recuperación. Una descripción de los modos y cómo utilizarlos está disponible en la documentación de PDOStatement::fetch().

Parámetros

attribute

El atributo a modificar.

value

El valor al que definir el attribute, esto puede requerir un tipo específico dependiendo del atributo.

Valores devueltos

Esta función retorna true en caso de éxito o false si ocurre un error.

Ver también

add a note

User Contributed Notes 8 notes

up
125
colinganderson [at] gmail [dot] com
18 years ago
Because no examples are provided, and to alleviate any confusion as a result, the setAttribute() method is invoked like so:

setAttribute(ATTRIBUTE, OPTION);

So, if I wanted to ensure that the column names returned from a query were returned in the case the database driver returned them (rather than having them returned in all upper case [as is the default on some of the PDO extensions]), I would do the following:

<?php
// Create a new database connection.
$dbConnection = new PDO($dsn, $user, $pass);

// Set the case in which to return column_names.
$dbConnection->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
?>

Hope this helps some of you who learn by example (as is the case with me).

.Colin
up
36
yeboahnanaosei at gmail dot com
7 years ago
This is an update to a note I wrote earlier concerning how to set multiple attributes when you create you PDO connection string.

You can put all the attributes you want in an associative array and pass that array as the fourth parameter in your connection string. So it goes like this:
<?php
$options
= [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_CASE => PDO::CASE_NATURAL,
PDO::ATTR_ORACLE_NULLS => PDO::NULL_EMPTY_STRING
];

// Now you create your connection string
try {
// Then pass the options as the last parameter in the connection string
$connection = new PDO("mysql:host=$host; dbname=$dbname", $user, $password, $options);

// That's how you can set multiple attributes
} catch(PDOException $e) {
die(
"Database connection failed: " . $e->getMessage());
}
?>
up
16
yeboahnanaosei at gmail dot com
7 years ago
Well, I have not seen it mentioned anywhere and thought its worth mentioning. It might help someone. If you are wondering whether you can set multiple attributes then the answer is yes.

You can do it like this:
try {
$connection = new PDO("mysql:host=$host; dbname=$dbname", $user, $password);
// You can begin setting all the attributes you want.
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$connection->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
$connection->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_EMPTY_STRING);

// That's how you can set multiple attributes
}
catch(PDOException $e)
{
die("Database connection failed: " . $e->getMessage());
}

I hope this helps somebody. :)
up
16
gregory dot szorc at gmail dot com
18 years ago
It is worth noting that not all attributes may be settable via setAttribute(). For example, PDO::MYSQL_ATTR_MAX_BUFFER_SIZE is only settable in PDO::__construct(). You must pass PDO::MYSQL_ATTR_MAX_BUFFER_SIZE as part of the optional 4th parameter to the constructor. This is detailed in http://bugs.php.net/bug.php?id=38015
up
1
Anonymous
3 years ago
Note that contrary to most PDO methods, setAttribute does not throw a PDOException when it returns false.
up
5
steve at websmithery dot co dot uk
8 years ago
For PDO::ATTR_EMULATE_PREPARES, the manual states a boolean value is required. However, when getAttribute() is used to check this value, an integer (1 or 0) is returned rather than true or false.

This means that if you are checking a PDO object is configured as required then

<?php
// Check emulate prepares is off
if ($pdo->getAttribute(\PDO::ATTR_EMULATE_PREPARES) !== false) {
/* do something */
}
?>

will always 'do something', regardless.

Either

<?php
// Check emulate prepares is off
if ($pdo->getAttribute(\PDO::ATTR_EMULATE_PREPARES) != false) {
/* do something */
}
?>

or

<?php
// Check emulate prepares is off
if ($pdo->getAttribute(\PDO::ATTR_EMULATE_PREPARES) !== 0) {
/* do something */
}
?>

is needed instead.

Also worth noting that setAttribute() does, in fact, accept an integer value if you want to be consistent.
up
12
antoyo
14 years ago
There is also a way to specifie the default fetch mode :
<?php
$connection
= new PDO($connection_string);
$connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
?>
up
-1
david at datava dot com
1 year ago
Note that in order for
\PDO::ATTR_TIMEOUT
to have any effect, you must set

\PDO::ATTR_ERRMODE=>\PDO::ERRMODE_EXCEPTION.

If

\PDO::ATTR_ERRMODE=>\PDO::ERRMODE_WARNING

it doesn't appear to do anything.
To Top