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
Unlike your old code it will not die with useless message but it will either
... 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.