patternphpMinor
Implementing PDO, code correct so far?
Viewed 0 times
correctfarcodeimplementingpdo
Problem
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
query.php
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
true
));
$DBH -> exec("set names utf8");
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>query.php
try {
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->beginTransaction();
$STH = $DBH->prepare('SELECT id from users where uid = :uid');
$STH->setFetchMode(PDO::FETCH_ASSOC);
$STH->bindParam(':uid', $uid); // $uid value is set
$STH->execute();
$uid_in_db = $STH->rowCount();
if($uid_in_db==0){ //=new user, insert info in db.
$STH = $DBH->prepare("INSERT INTO USERS (uid,namn) VALUES (:uid, :name)");
$STH->bindParam(':uid', $uid);
$STH->bindParam(':namn', $_POST['namn']); // a value posted form user input
$STH->execute();
}
$DBH->commit(); //
} catch (Exception $e) {
$DBH->rollBack();
echo "Fel: " . $e->getMessage();
}
}else{
$error=1;
}Solution
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->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //prepare("INSERT INTO USERS (uid,namn) VALUES (:uid, :name)");
$STH->bindParam(':uid', $uid);
$STH->bindParam(':namn', $_POST['namn']); // a value posted form user input
try {
$STH->execute();
} catch( PDOException $e ) {
//deal with collision
}Code Snippets
//you can remove the outer try/catch since only the execute() should possibly fail
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //<~ put this in the initialize of the db connection
$STH = $DBH->prepare("INSERT INTO USERS (uid,namn) VALUES (:uid, :name)");
$STH->bindParam(':uid', $uid);
$STH->bindParam(':namn', $_POST['namn']); // a value posted form user input
try {
$STH->execute();
} catch( PDOException $e ) {
//deal with collision
}Context
StackExchange Code Review Q#1949, answer score: 3
Revisions (0)
No revisions yet.