prepare php code example

Example 1: php mysql prepare query

$stmt = $mysqli->prepare("SELECT * FROM myTable WHERE name = ? AND age = ?");
$stmt->bind_param("si", $_POST['name'], $_POST['age']);
$stmt->execute();
$stmt->close();

Example 2: pdo prepare

<?php
/* Execute a prepared statement by passing an array of values */
$sql = 'SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
$sth->execute(array(':calories' => 175, ':colour' => 'yellow'));
$yellow = $sth->fetchAll();
?>

Example 3: preared request pdo

<?php
/* Exécute une requête préparée en passant un tableau de valeurs */
$sql = 'SELECT nom, couleur, calories
    FROM fruit
WHERE calories < :calories AND couleur = :couleur';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':couleur' => 'red'));
$red = $sth->fetchAll();
$sth->execute(array(':calories' => 175, ':couleur' => 'yellow'));
$yellow = $sth->fetchAll();
?>

Tags:

Sql Example