An alternative to mysqli, pdo offers the ability to create php “context variables”. here is an example
this example really worked right out of the box for me – that was very impressive. also, i really like the use of “try” & “catch”
<?php/*** mysql hostname ***/
$hostname = ‘localhost’;/*** mysql username ***/
$username = ‘username’;/*** mysql password ***/
$password = ‘password’;// database
$database = ‘animalDatabase’;try {
. . . $dbh = new PDO (“mysql:host=$hostname;dbname=$database”, $username, $password);
. . . /*** echo a message saying we have connected ***/
. . . echo ‘Connected to database
‘;. . . /*** set the error reporting attribute ***/
. . . $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);. . . /*** some variables ***/
. . . $animal_id = 6;
. . . $animal_name = ‘bruce’;. . . /*** prepare the SQL statement ***/
. . . $stmt = $dbh->prepare(“SELECT * FROM animals WHERE animal_id = :animal_id AND animal_name = :animal_name”);. . . /*** bind the paramaters ***/
. . . $stmt->bindParam(’:animal_id’, $animal_id, PDO::PARAM_INT);
. . . $stmt->bindParam(’:animal_name’, $animal_name, PDO::PARAM_STR, 5);. . . /*** reassign the animal_id ***/
. . . $animal_id = 3;. . . /*** execute the prepared statement ***/
. . . $stmt->execute();. . . /*** loop over the results ***/
. . . while($row = $stmt->fetch()) {
. . . . . . echo $row[‘animal_id’].’
‘;
. . . . . . echo $row[‘animal_type’].’
‘;
. . . . . . echo $row[‘animal_name’];
. . . }. . . /*** close the database connection ***/
. . . $dbh = null;
} catch(PDOException $e) {
. . . echo $e->getMessage();
}
? >