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

$dbhost        = "localhost";

$dbname        = "pdo";

$dbuser        = "root";

$dbpass        = "";

// 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:
<?php

// configuration

$dbhost        = "localhost";

$dbname        = "pdo";

$dbuser        = "root";

$dbpass        = "";

// database connection

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

$title = 'PHP%';

$author = 'Bobi%';

// query

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

$q = $conn->prepare($sql);

$q->execute(array($title,$author));

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

// fetch

while($r = $q->fetch()){

print_r($r);

echo"<br>";

}

?>


0 comments:

Post a Comment

 
Top
Blogger Template