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

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

1.最简单的方式


  1. php
  2. $con = mysql_connect("localhost","root","");
  3. if (!$con)
  4. {
  5. die('Could not connect: ' . mysql_error());
  6. }
  7. mysql_close($con);
  8. ?>

2.面向对象mysqli(详细教程)


  1. php
  2. $mysqli = new mysqli('localhost','root','','volunteer');
  3. if (mysqli_connect_errno()){
  4. die('Unable to connect!'). mysqli_connect_error();
  5. }
  6. ?>

3.pdo连接mysql(详细教程)


  1. php
  2.  
  3. $db = new PDO('mysql:host=localhost;dbname=test', 'root', '');
  4. try {
  5. foreach ($db->query('select * from user') as $row){
  6. print_r($row);
  7. }
  8. $db = null; //关闭数据库
  9. } catch (PDOException $e) {
  10. echo $e->getMessage();
  11. }
  12. ?>

4.ADODB连接mysql(详细教程)


  1. php
  2. require_once './adodb5/adodb.inc.php';
  3. $conn = &ADONewConnection('mysql');
  4. $conn->connect('localhost','root','','test');
  5. $conn->Execute("set names utf8");
  6. $res = $conn->Execute("select * from user");
  7. if (!$res){
  8. echo $conn->ErrorMsg();
  9. }else{
  10. var_dump($res);
  11. }
  12. ?>

你可能感兴趣的:(数据库,PHP)