Skip to content
Advertisement

PHP PDO access to MySQL

I went through the process of converting mysql_* code into PDO code. I’ve run it and checked that it works and everything. I just want Stack Overflow’s review of it, to make sure that I’m killing the connection properly, whether I should use some other method instead (e.g. transactions), making sure there are not massive security flaws. Here’s the code:

<?php
    try {
        $link = new PDO('mysql:****;dbname=****;charset=UTF-8','****','****');
        $link->exec("INSERT INTO Registration (`First Name`, `Last Name`) VALUES ('$_POST[fname]', '$_POST[lname]')");
    } catch(PDOException $e) {
        print "Error!: " . $e->getMessage() . "<br/>";
        die();
    }
?>

Like I said, it works, but I want it to be safe and effective when 100 people register at the same time. Does everything look okay?

Advertisement

Answer

No .. you are converting mysql_ to PDO 1:1. This way, issues in mysql_ will also be a issue in PDO.

You should look at prepared queries and parameter binding.

Here is a example of what I mean:

$dbh = new PDO('mysql:****;dbname=****;charset=UTF-8','****','****');

$first = 'John';
$last = 'Doe';

$stmt = $dbh->prepare(
   "INSERT INTO Registration (firstname, lastname) VALUES (:first, :last)");
$stmt->bindParam(':first', $first);
$stmt->bindParam(':last', $last);

$stmt->execute();

// insert another row with different values
$first = 'John';
$last = 'Smith';
$stmt->execute();
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement