1.最簡單的方式-mysql(面向過程)php
<?php $con = mysql_connect("localhost","root","password"); $select_db = mysql_select_db('test'); if (!$select_db) { die("could not connect to the db:\n" . mysql_error()); } //查詢代碼 $sql = "select * from db_table"; $res = mysql_query($sql); if (!$res) { die("could get the res:\n" . mysql_error()); } while ($row = mysql_fetch_assoc($res)) { print_r($row); } //查詢代碼 //關閉數據庫鏈接 mysql_close($con); ?>
2.新的方式-mysqli(面向過程)mysql
$mysql_server_name = 'localhost'; //改爲本身的mysql數據庫服務器 $mysql_username = 'root'; //改爲本身的mysql數據庫用戶名 $mysql_password = 'password'; //改爲本身的mysql數據庫密碼 $mysql_database = 'test'; //改爲本身的mysql數據庫名 $conn=mysqli_connect($mysql_server_name,$mysql_username,$mysql_password,$mysql_database); //鏈接數據庫 //鏈接數據庫錯誤提示 if (mysqli_connect_errno($conn)) { die("鏈接 MySQL 失敗: " . mysqli_connect_error()); } mysqli_query($conn,"set names utf8"); //數據庫編碼格式 // mysqli_set_charset($conn,"utf8");//設置默認客戶端字符集。 // mysqli_select_db($conn,$mysql_database); //更改鏈接的默認數據庫 //查詢代碼 $sql = 「select * from db_table」; $query = mysqli_query($conn,$sql); while($row = mysqli_fetch_array($query)){ echo $row['title']; } //查詢代碼 // 釋放結果集+關閉MySQL數據庫鏈接 mysqli_free_result($result); mysqli_close($conn);
三、經常使用方式-mysqli(面向對象)sql
//鏈接數據庫方式1 $conn = new mysqli('localhost', 'root', 'password', 'test'); //鏈接數據庫方式2 // $conn = new mysqli(); // $conn -> connect('localhost', 'root', 'password', 'test'); //check connection (檢查PHP是否鏈接上MYSQL) if ($conn -> connect_errno) { printf("Connect failed: %s\n", $conn->connect_error); exit(); } //查詢代碼 $sql = 「select * from db_table」; $query = $conn->query($sql); while($row = $query->fetch_array()){ echo $row['title']; } //查詢代碼 //釋放結果集+關閉MySQL鏈接 $query1 -> free_result(); $conn -> close();
四、PDO鏈接MySQL數據庫數據庫
<?php $db = new PDO('mysql:host=localhost;dbname=test', 'root', 'password'); try { foreach ($db->query('select * from db_table') as $row){ print_r($row); } $db = null; //關閉數據庫 } catch (PDOException $e) { echo $e->getMessage(); } ?>
五、ADODB鏈接MySQL數據庫服務器
<?php //安裝驅動-引入類便可 require_once './adodb5/adodb.inc.php'; $conn = &ADONewConnection('mysql'); $conn->connect('localhost','root','password','test'); $conn->Execute("set names utf8"); //查詢代碼 $res = $conn->Execute("select * from db_table"); if (!$res){ echo $conn->ErrorMsg(); }else{ var_dump($res); } ?> //關閉鏈接 $conn->close();
六、總結-關閉mysql數據庫的鏈接方法fetch
MySQL - 面向過程 mysql_close($conn); MySQLi - 面向過程 mysqli_close($conn); MySQLi - 面向對象 $conn->close(); PDO $conn = null; ADODB $conn->close(); 或 $conn->free();