如何从mysql实现或切换到PDO [关闭]

In my case, I am building a website and started off with mysql. How do you code a web site use PDO API instead of mysql API? What are the equivalents of mysql commands in PDO?

For instances like:

$query = mysql_query(INSERT INTO users Values ('','$un','$fn','$ln','$em','$pswd','d','0')");

What would be the correct PDO syntax when you have '' and '0'?

mysql_connect.inc.php

$db = new PDO('mysql:host=localhost;dbname=socialnetwork', 'root', 'abc123');

Then, anywhere you have a mysql_query, you'll need to use the PDO Query Methods. I'll show an example:

index.php

// instead of:
$u_check = mysql_query("SELECT username FROM users WHERE username='$un'");

// use:
$statement = $db->prepare('SELECT username FROM users WHERE username = :username');
if ($statement->execute(array(':username' => $un))) {
  // query succeeded
  if ($statement->rowCount() > 0){
    // user exists
  }
}

It's just a matter of replacing the mysql_* with PDO statements and using that API instead.

Basic Synopsis:

mysql [ext] has significant security exploits

Nope, it doesn't.
Mysql ext would be as good or as bad as a developer using it.
But there is nothing like "significant security exploits".

So, there is a quick fix: As long as you're adding to your query quoted strings only, and always properly format them (using mysql_real_escape_string) - you're pretty safe.

Most of the code you posted wont need to change except the following:

mysql_connect.inc.php (new connect string) and anywhere you call 'mysql_query'

You'll need a wrapper class (try this one - PDO wrapper) to convert the straight sql to a prepared statement