Saturday, February 21, 2015

PDO - Full Snippet

This is fully working snippet for PDO Select with parameters

<?php
$username = "user_name";
$password = "password";
$hostname = "localhost";
$dataBase = "data_base_name";
$character_set = "utf8";
$id = 8;
$slug = "string";
try {
 $conn = new PDO("mysql:host=$hostname;dbname=$dataBase;charset=$character_set", $username, $password);
 $conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 $stmt = $conn -> prepare("SELECT * FROM table_name WHERE id = :id AND slug=:slug");
 $stmt->bindParam(":id", $id, PDO::PARAM_INT);
 $stmt->bindParam(":slug", $slug, PDO::PARAM_STR); 
 $stmt->execute();
 echo "Query has: ".$stmt -> rowCount() . " rows <hr>";
 while ($row = $stmt -> fetch()) {
  echo $row['id'] . " - " . $row['slug'] . "\n<br>";
 }
} catch(PDOException $e) {
 echo 'ERROR: ' . $e -> getMessage();
}
?>

No comments:

Post a Comment