php连接mysql数据库的几种方法

分享几种最常见的mysql链接方式!

1、简单直接

$link = mysql_connect("localhost","root","123456");
if (!$link){
	die('Could not connect: ' . mysql_error());
}
/*
mysql_select_db('data_name', $link);
$result = mysql_query('SELECT id, title FROM table', $link);
*/
mysql_close($link);

2、mysqli面向对象

$mysqli = new mysqli('localhost','root','','data_name');
if (mysqli_connect_errno()){
	die('Unable to connect!'). mysqli_connect_error();
}

3、pdo连接mysql

$db = new PDO('mysql:host=localhost;dbname=data_name', 'root', '');
try {
	foreach ($db->query('select * from user') as $row){
		print_r($row);
	}
	$db = null;  //关闭数据库
} catch (PDOException $e) {
	echo $e->getMessage();
}

4、ADODB连接mysql

require_once './adodb5/adodb.inc.php';
$conn = &ADONewConnection('mysql');
$conn->connect('localhost','root','','data_name');
$conn->Execute("set names utf8");
$res = $conn->Execute("select * from user");
if (!$res){
	echo $conn->ErrorMsg();
}else{
	var_dump($res);
}