sql >> Base de Datos >  >> RDS >> Mysql

¿Cómo recorro una consulta MySQL a través de PDO en PHP?

Aquí hay un ejemplo para usar PDO para conectarse a una base de datos, decirle que arroje excepciones en lugar de errores de php (lo ayudará con su depuración) y usar declaraciones parametrizadas en lugar de sustituir valores dinámicos en la consulta usted mismo (altamente recomendado):/P>

// connect to PDO
$pdo = new PDO("mysql:host=localhost;dbname=test", "user", "password");

// the following tells PDO we want it to throw Exceptions for every error.
// this is far more useful than the default mode of throwing php errors
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// prepare the statement. the placeholders allow PDO to handle substituting
// the values, which also prevents SQL injection
$stmt = $pdo->prepare("SELECT * FROM product WHERE productTypeId=:productTypeId AND brand=:brand");

// bind the parameters
$stmt->bindValue(":productTypeId", 6);
$stmt->bindValue(":brand", "Slurm");

// initialise an array for the results
$products = array();
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $products[] = $row;
}