What is the best way to connect to and query a MySQL database using PHP?

mysql, php

Solution

By far the best way is to use prepared statements. You can do this using PDO or mysqli, but I prefer the PDO extension for its named parameters.

Why are prepared statements by far the best way? Because they take care of parameter quoting and escaping for you.

Bad, old, error-prone, tedious way:

$result = mysql_query("SELECT * FROM users WHERE 
                       password='".mysql_real_escape_string($password)."'");

You can bet that, if you've written an application like this, you will have forgotten at some point to escape the user input, and left a gaping SQL injection hole.

Nice prepared statement way:

$stmt = $dbh->prepare("SELECT * FROM users WHERE password=:password");
$stmt->bindParam(':password', $password);
$stmt->execute();

Escaping is done for you, and you don't even have to worry about putting quotes around the parameter types that need them.

Problem

This is a pretty easy question but I would like some clarity on something. I have seen a number of different ways to connect and query a MySQL Database using PHP but which is the best way to connect and create a query using PHP?

Original source