phpeveryday.com

The best tutorial of php, php framework, php strategies, object oriented oriented,


PDO: Prepared Statement

Tag: PHP Data Objects, PDO, extension, PHP extension, query, statement   Category: PHP Database
post: 19 Apr 2008 read: 1,112


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));



| Give Your Opinion | Recommend
Share and Bookmark to: These icons link to social bookmarking sites where readers can share and discover new web pages.
digg del.icio.us technorati Ma.gnolia BlinkList

Recommended articles by other readers:
Web Services: How PHP Kiss VB.NET? (Part 1)
Chart: How to Build Cool Animation Real Time Chart
Joomla: Fast Road to Understand Component Programming
Email: Send Attachement Mail
SMS : Sending SMS with PHP and ActiveXperts (Part 1)

What do You Think?
Your Name *:
Email *:
(Will not be published)
Website/URL:
Your Comment *:
* Required


624
posting