1

I find a lot of questions on here relating to MySQL and designing queries, and the first thing that we always tell them is "Don't use the mysql_* functions - they're being deprecated." So I thought I would add a quick guide to setting up a PDO connection in your PHP program so that we can refer new PHP developers here, and help make their programs more secure.

Those experience in PHP and PDO, please feel free to edit and add where necessary to make this more useful for beginners in PDO.

SamHuckaby
  • 1,162
  • 1
  • 13
  • 35
  • 1
    BTW `mysql_()` are not yet deprecated... – Mr. Alien Oct 31 '12 at 18:52
  • @Mr.Alien Good point, I've modified the question to reflect that. – SamHuckaby Oct 31 '12 at 18:53
  • Great :) and I guess this question may be closed as these types of questions were allowed before but they are now marked as **Not Constructive**, read **FAQ** – Mr. Alien Oct 31 '12 at 18:54
  • Oh, I only added it because it gives you the option at the bottom of the question page. I didn't feel like it was out of step with the FAQ, but if that's the case, I will delete it. – SamHuckaby Oct 31 '12 at 18:56
  • If you think it might be closed as "not constructive" flag it as wiki – Mark Baker Oct 31 '12 at 18:57
  • Why repeat things? [**Please, don't use `mysql_*` functions in new code**](http://bit.ly/phpmsql). They are no longer maintained and the [deprecation process](http://j.mp/Rj2iVR) has begun on it. See the [**red box**](http://j.mp/Te9zIL)? Learn about [*prepared statements*](http://j.mp/T9hLWi) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://j.mp/QEx8IB) will help you decide which. If you choose PDO, [here is a good tutorial](http://j.mp/PoWehJ). – Anthony Hatzopoulos Oct 31 '12 at 18:57
  • @MarkBaker How do I flag it as wiki? I'm afraid I've never done it before. – SamHuckaby Oct 31 '12 at 19:01

1 Answers1

4

Step 1: Setting up a new PDO connection

This is not nearly as hard as it is sometimes made out to be. To begin with, you can hunt down those mysql_connect/mysql_select_db and replace them with this code:

//Obviously, replace these with your own values
$host = 'host_name';
$dbname = 'database_name';
$user = 'user_name';
$pass = 'user_pass';
try
{
    $DB = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); 
}
catch(PDOException $e)
{  
    echo $e->getMessage();  
}

This will create your PDO object which has all the same functionality of the mysql_* calls and then some.

Step 2: Submitting a query

once you have your PDO object, you can begin using it to query your database. We'll look at a basic select query first, since the techniques we'll use are similar in most query types. Now, you can query directly, but that takes away some of the power of PDO. Instead, we can use prepared statements. By doing so, PDO will work for us to prevent injection or even accidental query breakage. Here's an example:

$query = "SELECT * FROM table_name WHERE col1=':value1' AND col2=':value2'";
$statement = $DB->prepare($query);
$statement->execute(array(':value1' => 1, ':value2' => 2));

At this point, we've queried the database, and have a statement object with the results in it. The bonus here is that, in place of 1 or 2 in the execute statement, we could use a user-generated value, without even checking for SQL injection attempts, because PDO catches them and fixes them automatically. (Though, granted, you should still check that they exist before using user-generated values.)

Step 3: Retrieving the results

Now, we need to get the data we were searching for, so we can use it. With PDO it's quite simple, all you need is to call the fetch command, just like you would have used that mysql_fetch_array() command before. You'll also want to include it in a while loop to retrieve all the results, since it acts almost identically to mysql_fetch_array().

//You can use several options in fetch, to determine what kind of results you get.
//PDO::FETCH_ASSOC -> gives you column names as the array indices
//PDO::FETCH_NUM   -> Gives you the column number as the indices
// By default, it uses PDO::FETCH_BOTH which does both.
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
     echo "Col1: " . $row['col1'] . "<br />";
     echo "Col2: " . $row['col2'] . "<br />";
     echo "Col3: " . $row['col3'] . "<br />";
     echo "Col4: " . $row['col4'];
}

Obviously, this is a pretty simple layout, but you can see how it works, and can modify it for your needs. This does exactly the same thing as your current mysql_* code does, except it does it in a simpler more secure manner.

Step 4: The possibilities

From here, you can see how to replace your basic mysql_* functions. You can replace all other mysql functions with PDO calls as well, a few examples are:

mysql_num_rows() == $statement->rowCount() (used after you've executed your query) mysql_real_escape_string() == You don't even need this anymore!
mysql_insert_id() == $statement->lastinsertid()

The definitive guide to PHP's PDO usage can be found here:
http://us3.php.net/manual/en/book.pdo.php

And here is a question that looks at the strengths and weaknesses of mysqli vs PDO:
mysqli or PDO - what are the pros and cons?

Community
  • 1
  • 1
SamHuckaby
  • 1,162
  • 1
  • 13
  • 35
  • `rowCount` is unreliable. Better use `COUNT` query and retrieve the number. – itachi Oct 31 '12 at 18:58
  • I favor `mysqli` over `PDO`. IMO, PDO is like the lowest common denominator while mysqli is dedicated :) Once you use more complex queries and make your code MySQL only... you start seeing the benefits. Takes a bit more handy work though... `PDO` is more noob friendly but `mysqli` with the right wrapper kicks S. – CodeAngry Oct 31 '12 at 19:06
  • @Claudrian erm.... what? – itachi Oct 31 '12 at 19:23
  • @itachi I'll break it down for you: `if(used_to_use(mysql_*)) use(mysqli_*);`. It's slightly faster than PDO for most real life usage scenarios. `// <- END OF STORY` _(I can even draw it if you want)_ – CodeAngry Oct 31 '12 at 19:27
  • @Claudrian `if(used_to_use(mysqli_*)) use(PDO) //<---- END OF STORY`. but wait.... moral of the story hasn't come yet. So here's the moral, if you are not building a website where migration can become an issue, then use big brother of mysqli, i.e. `PDO`. **mysqli is limited** `//<---- THE END` _(i can't draw even if you insist)_ – itachi Oct 31 '12 at 19:41
  • @itachi Looking forward to the **limitation list/link**... (drawing is optional) – CodeAngry Oct 31 '12 at 19:44
  • @Claudrian look the name..... **mysql** i – itachi Oct 31 '12 at 19:45
  • @itachi Cute! Whatever... Do some tests. I'm currently writing a wrapper and micro-timed queries (as in fetches, inserts, transactions, etc.) and chose mysqli vs PDO after tried both. Plus it's a lot easier to use as it makes sense for a C++ developer that uses the mysql C library. – CodeAngry Oct 31 '12 at 19:53
  • @Claudrian why you are assuming database will always be mysql? mysql is not an absolute standard. if you want to change database system later, good luck writing the codes again in `PDO`. – itachi Oct 31 '12 at 19:58