Todays update is all about databases and using MySQLi with prepared statements instead of using MySQL and mysql_connect. There are already a bunch of discussions about prepared statements so I will not go into details here. Basically it helps us protect our site against SQL injections, it runs faster and when preparing a statement the database will optimize the execution for the query.

Instead of going through all the details, which you can find on php.net or if you do a quick search on “php prepared statements”, I will give you a code example of what I use in my everyday work.


function fetch($query) {
if($stmt = $this->connection->prepare($query)) {
$results = array();
$stmt->execute();
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field())
$parameters[] = &$row[$field->name];
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while ($stmt->fetch()) {
$record = new StdClass;
foreach($row as $key => $value)
$record->$key = $value;
$results[] = $record;
}
$stmt->close();
return $results;
}
return null;
}

What this piece of code does it that it will let you to bind variables to your SQL statement dynamically so you don’t need to specify the variables you want to be able to use when you call your prepared statement. $this->connection in this case is my mysqli object. The content is from my mysqli database class. After calling this method “fetch” we are able to loop through a array of stdClass objects.

Hope you will enjoy this!

About these ads