mysql - PHP - Beginning Prepared Statements but they seem unwieldy -


i've got website connect mysql database make number of queries, in usual fashion. i'm not doing more complicated than:

$result = mysql_query('select * table condition = "'.mysql_real_escape_string($_post['condition']).'"'); $row = mysql_fetch_assoc($result); echo $row['var1'].' '.$row['var2']; 

and works. i've been reading prepared statements , seem offer more security , i'd use them , replace database calls prepared statements, i've been looking @ mysqli class.

but seem more code achieve same thing. understand i'd have above:

$stmt = $db->stmt_init(); if($stmt->prepare('select * table condition = ?')) { $condition = $_post['condition']; $stmt->bind_param('s', $condition); $stmt->execute();  $stmt->bind_result($var1, $var2, ...); if ($stmt->fetch()) {     echo $var1 . ' - ' . $var2; } } 

so seems hell of lot more code, , bit harder manage. misunderstanding how use these or there shorter way of doing "normal" php things:

  • populating $row, being array representing 1 single line database.
  • looping on rows, , refilling $row "next row" along.
  • normal update enquiries.

the above nice , quick "normally" seem take many more lines using prepared statements.

a common way wrap database functionality class. here's simple 1 implementing caching of prepared statements:

class db {   protected $db;   protected $cache;    public function __construct($host, $database, $user, $pass, $charset = 'utf8') {     $this->db = new pdo(sprintf('mysql:dbname=%s;host=%s', $database, $host, $charset),                         $user, $pass);     $this->cache = array();     $this->db->query(sprintf('set names %s', $charset));   }    public function query($query, $vars = array()) {     //you may input simple value, no need arrays single argument                                   if (!is_array($vars))       $vars = array($vars);      //short names inside function                                                                           $db = &$this->db;     $cache = &$this->cache;      //ensure prepared statement in cache                                                                 if (!isset($cache[$query]))       $cache[$query] = $db->prepare($query);      //execute statement , return rows                                                                 $stmt = $cache[$query];     if ($stmt->execute($vars))       return $stmt->fetchall();     else       return false;   } } 

usage of close older database interfaces. example:

$db = new db(host, database, user, pass); $result = $db->query('select id, name table id = ? , address = ?',                      array(42, 'home')); foreach ($result $row) {   ... } 

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -