PDO: Prepared Statement


PHP Data Objects (PDO) Step By Step Tutorial - Part 7: Do you ever hear about prepared statements? If you ever work with other tool such visual studio, may be you use prepare statement. PHP Extension for MySQL and SQLite don't offer this functionality. Ok, I will show a sample. I believe, from that sample you will understand what is prepare statement.
<?php
// configuration
$dbtype		= "sqlite";
$dbhost 	= "localhost";
$dbname		= "test";
$dbuser		= "root";
$dbpass		= "admin";

// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

$title = 'PHP AJAX';

// query
$sql = "SELECT * FROM books WHERE title = ?";
$q = $conn->prepare($sql);
$q->execute(array($title));


$q->setFetchMode(PDO::FETCH_BOTH);

// fetch
while($r = $q->fetch()){
  print_r($r);
}


?>

in this simple example, query depends on a variabel (we write with ?).

$sql = "SELECT * FROM books WHERE title = ?";

Now, we manipulate this query to create the prepared statement and execute it:

$q = $conn->prepare($sql);
$q->execute(array($title))

Another sample:

$title = 'PHP%';
$author = 'Bobi%';
// query
$sql = "SELECT * FROM books WHERE title like ? AND author like ? ";
$q = $conn->prepare($sql);
$q->execute(array($title,$author));

Previous: PDO: Error Handling
Next: PDO: Positional and Named Placeholders



Series this article:
PDO: Introduction PHP Data Object
PDO: Activation PHP Data Objects Extension
PDO: Connecting Use PHP Data Object
PDO: Portable Connection to Database
PDO: Posibble Fetch Mode
PDO: Error Handling
PDO: Prepared Statement
PDO: Positional and Named Placeholders
PDO: Insert and Update Statement Use Prepared Statement
PDO: Prepared Statement and Bound Values
PDO: Working With BLOBs
PDO: Alternative Retrieve BLOB Data
PDO: Setting Connection Attributes
PDO: Error Mode Attributes
PDO: Improve Performance with Persistent Connection
PDO: Getting Connection Attributes

Bookmark and Share Tag: PHP Data Objects, PDO, extension, PHP extension, query, statement Category: PHP Database Post : April 19th 2008 Read: 119,519

advertisements


blog comments powered by Disqus