以下是本人总结的php连接mysql数据库的4种方法,包括最常用的普通方法、mysqli连接、PDO连接和ADODB连接方式。

<?php
$dbhost = "127.0.0.1";
$dbuser = "root";
$password = "root";
$dbname = "ecshop";

/*
1、最常见的方法(面向过程)
注:PHP5.5.0起废弃此方法!
*/
$link = mysql_connect($dbhost, $dbuser, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connect MySQL successfully!'."<hr />";
mysql_select_db($dbname);

//mysql_close($link);

/*
2、面向对象风格
*/
$mysqli = new mysqli($dbhost,$dbuser,$password,$dbname);
if(mysqli_connect_error()){
die ('Could not connect MySQL.' . $mysqli->connect_error);
}
echo 'Connect MySQL successfully!'."<hr />";

//$mysqli->close();

/*
3、PDO连接MySQL
*/
$pdo_link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser,$password);

try {
$dsn = 'mysql:dbname=ecshop;host=127.0.0.1'; //单引号不解析里面的变量,会原样输出字符串
$pdo_connect = new PDO($dsn, $dbuser,$password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
echo 'Connect MySQL successfully!'."<hr />";

/*
4、ADODB连接MySQL
*/
require_once '../ADOdb/adodb.inc.php';
$dbdriver = 'mysql';
$adodb_link = ADONewConnection($dbdriver);
$adodb_link->connect($dbhost,$dbuser,$password,$dbname);

if (!$adodb_link){
echo $adodb_link->ErrorMsg();
}else{
echo 'Connect MySQL successfully!';
}

/* 还有第三方类库连接MySQL(在此不述) */