Implementing PDO, code correct so far? I have decided to go PDO and have started implementing it on one of my webprojects. I have limited programing skills but can usually pull it off with some tutorials and forums.

Here is my code this far and it works fine but how is the code correct regarding the picking up errors, syntax, order and begintransaction etc.? Have I missunderstood anything? Is anything unneccesary?

connect.php

 &lt;?php
try {
    $DBH = new PDO("mysql:host=$host;dbname=$database", $username, $password, array(
        PDO::ATTR_PERSISTENT =&gt; true
    ));
    $DBH -&gt; exec("set names utf8");
}
catch(PDOException $e) {
    echo $e-&gt;getMessage();
}
?&gt;


query.php

try {  
        $DBH-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $DBH-&gt;beginTransaction();   

        $STH = $DBH-&gt;prepare('SELECT id from users where uid = :uid');
        $STH-&gt;setFetchMode(PDO::FETCH_ASSOC); 
        $STH-&gt;bindParam(':uid', $uid); // $uid value is set
        $STH-&gt;execute();

        $uid_in_db = $STH-&gt;rowCount();
        if($uid_in_db==0){ //=new user, insert info in db.
            $STH = $DBH-&gt;prepare("INSERT INTO USERS (uid,namn) VALUES (:uid, :name)");
            $STH-&gt;bindParam(':uid', $uid);
            $STH-&gt;bindParam(':namn', $_POST['namn']); // a value posted form user input
            $STH-&gt;execute();
        }

        $DBH-&gt;commit(); // 

    } catch (Exception $e) {
        $DBH-&gt;rollBack();
        echo "Fel: " . $e-&gt;getMessage();
    }
}else{
    $error=1;
}
Instead of checking for a UID collision before an insert, I would put a unique key on that column, and then write fallback code for the case (very very unlikely) when two collide. That way you can simplify your logic and reduce the number of queries to one instead of two. You also don't need a transaction if you implement this change, since there is only 1 query.

//you can remove the outer try/catch since only the execute() should possibly fail
$DBH-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //&lt;~ put this in the initialize of the db connection
$STH = $DBH-&gt;prepare("INSERT INTO USERS (uid,namn) VALUES (:uid, :name)");
$STH-&gt;bindParam(':uid', $uid);
$STH-&gt;bindParam(':namn', $_POST['namn']); // a value posted form user input
try {
    $STH-&gt;execute();
} catch( PDOException $e ) {
    //deal with collision 
}