简体   繁体   中英

How to make a database connection converting mysql to PDO?

Im trying to convert all my mysql code into PDO. First thing Im trying to convert to PDO is my database connection. Can somebody help me on the right way?....

Here comes my database connection in mysql:

  $host = "localhost"; 
$user = "root"; 
$password = "root";
$db = "blog";

$bd = mysql_connect($host, $user, $password) or die("Opps something wrong...");
mysql_select_db($db, $bd) or die("Opps something wrong...");

Have a look at the PHP Manual's PDO page , especially the part on 'Connections and Connection Management': http://www.php.net/manual/en/pdo.connections.php

$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);

or... use Captain Common Sense's approach :)

There is a PDO tag wiki where you can learn the right way (as well as many other useful things) from someone who had a real experience with PDO.

$dsn = "mysql:host=$host;dbname=$db;charset=utf8";
$opt = array(
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,$username,$password, $opt);

Unlike all other codes which are useless for handling connection errors (as they set exception mode after the actual connect) it will

  • make PHP throw an exception on connection error
  • will not reveal sensitive information to a potential attacker on a live server by echoing an error out.
  • provide you with indispensable stack trace .
  • set the connection encoding in the right place

Unlike your old code it will not die with useless message but it will either

  • die with useful error message on-screen
  • die with useful error message logged, leaving screen blank
  • die with useful error message logged, with conventional error page shown
  • not die at all but gracefully handled with designated handler function

... depends on the chosen settings.

Connection with error handling..

try {
    $conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);

OR

try {
    $conn = new PDO('mysql:host=localhost;dbname=blog', $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

More details Click here

你看过手册了吗?

$dbh = new PDO('mysql:host=localhost;dbname=yourdbname', 'youruser', 'yourpassword');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM