Recent Post

Categories

Archives

Cow Computing

10 Apr 4

PHP Data Object

Often time, when working on a website, certain database transactions have to be taken with great care (e.g. payment, account creation…). It’s definitely an advantage to make use of the Atomicity the database provides (e.g. mySQL). But How? Here’s i will show you how to use PDO to wrap a SQL insert statement such that it’s either done or no. (*it’s included with PHP5, and you have to enable the extension inside the php.ini)

<?php

$hostname = 'localhost';
$username = 'username';
$password = 'password';

try {
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);

// Setting the notification to throw exception when error encountered
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$dbh->beginTransaction();
$count = $dbh->exec("INSERT INTO user(userID, name) VALUES ('1', 'Steve')");
$dbh->commit();

$dbh = null;
}
catch(PDOException $e)
{
$dbh->rollback();
echo $e->getMessage();
}

?>