Sunday, April 7, 2013

Databases -> Prepared Statements

Prepared Statements consist of two stages

  1. Prepared Statement
  2. Execute Statement  
Prepared Statements : The statement template is created by the application and to database server. The Database server parses, compiles, and performs query optimization on the statement template, and stores the result without executing it.

Execute Statements : In this statement only execute. By doing this it save lot of time.

See following examples

//server name
$hostname='localhost';

//databse name
$dbname='abc';

//username of database
$username='root';

//password of database
$password='';
try {
    $db = new PDO("mysql:host=$hostname;dbname=$dbname",$username,$password);
    $db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES utf8");  
    
} catch (PDOException $e) {
    echo $e->getMessage();
}

//search text
$search='watch';

$q = $db->prepare('SELECT * FROM products WHERE name LIKE ?');
$q->execute(array('%'.$search.'%'));
$num = $q->rowCount();
if ($num > 0) {
  while ($row = $q->fetch()) {
    print_r($row);
  }
} else {
  echo "No Record";
}

No comments:

Post a Comment