PHP 5.5.0版之前的php+mysql的鏈接方法
1、基礎操做
- 發起會話
$conn = @mysql_connect($host,$name,$pwd);
- 選擇數據庫
@mysql_select_db($db,$conn);
- 設置參數(如:編碼)
mysql_query("set names gb2312"); //設置編碼
- 操做(CURL)
- 關閉會話
mysql_close($conn);
2、封裝類庫
目錄
| pro 項目目錄
| -- | mysql.php
| -- | index.php
文件mysql.php
<?php
//PHP 5.5.0版之前
class mysql {
private $host = 'localhost'; //服務器地址
private $name = 'root'; //登陸帳號
private $pwd = 'root'; //登陸密碼
private $db = 'db'; //數據庫名稱
private $conn = ''; //數據庫鏈接資源
private $result = ''; //結果集
private $msg = ''; //返回結果
private $fields; //返回字段
private $fieldsNum = 0; //返回字段數
private $rowsNum = 0; //返回結果數
private $rowsRst = ''; //返回單條記錄的字段數組
private $filesArray = array(); //返回字段數組
private $rowsArray = array(); //返回結果數組
function __construct($host='',$name='',$pwd='',$db=''){
if(!empty($host)) $this->host = $host;
if(!empty($name)) $this->name = $name;
if(!empty($pwd)) $this->pwd = $pwd;
if(!empty($db)) $this->db = $db;
$this->init_conn();
}
//鏈接數據庫
function init_conn(){
$this->conn = @mysql_connect($this->host,$this->name,$this->pwd);
@mysql_select_db($this->db,$this->conn);
mysql_query("set names gb2312"); //設置編碼
}
//查詢結果
function mysql_query_rst($sql){
if($this->conn == '') $this->init_conn();
$this->result = @mysql_query($sql,$this->conn);
}
//返回查詢記錄數函數
function getRowsNum($sql){
$this->mysql_query_rst($sql);
if(mysql_errno() == 0){
return @mysql_num_rows($this->result);
}else{
return '';
}
}
//取得記錄數函數
function getRowsRst($sql){
$this->mysql_query_rst($sql);
if(mysql_errno() == 0){
$this->rewsRst = mysql_fetch_array($this->result,MYSQL_ASSOC);
return $this->rewsRst;
}else{
return '';
}
}
//取得記錄數組(多條記錄)
function getRowsArray($sql){
$this->mysql_query_rst($sql);
if(mysql_errno() == 0){
while($row = mysql_fetch_array($this->result,MYSQL_ASSOC)){
$this->rowsArray[] = $row;
}
return $this->rowsArray;
}else{
return '';
}
}
//返回更新、刪除、添加的記錄數函數
function uidRst($sql){
if($this->conn == '') $this->init_conn();
@mysql_query($sql);
$this->rowsNum = @mysql_affected_rows();
if(mysql_errno() == 0){
return $this->rowsNum;
}else{
return '';
}
}
//釋放結果集函數
function close_rst(){
mysql_free_result($this->result);
$this->msg = '';
$this->fieldsNum = 0;
$this->rowsNum = 0;
$this->filesArray = '';
$this->rowsArray = '';
}
//關閉數據庫函數
function close_conn(){
$this->close_rst();
mysql_close($this->conn);
$this->conn = '';
}
}
?>
文件index.php
<?php
//使用方法
require_once('mysql.php');
$mysql = new mysql();
$sql = "SELECT * FROM `user` WHERE id=1";
var_dump($opmysql->getRowsRst($sql));
die();
?>