<?php
header('content-type:text/html;charset=utf-8');
error_reporting(E_ALL ^ E_DEPRECATED);
// 設計一個mysql數據庫操作類
$config=array(
'host'=>"localhost",
'port'=>3306,
'user'=>"root",
'pass'=>'',
'char'=>"utf8",
'db'=>"test"
);
class MYSQL{
private $link=null;
private $host;
private $port;
private $user;
private $pass;
private $char;
private $db;
function __construct($config){ //一實例化 就會連接上這個數據庫 把數組加載進來
// 把連接過來的數據庫信息保存起來,留以它用
$this->host=!empty($config['host']) ? $config['host'] : "localhost";
$this->port=!empty($config['port']) ? $config['port'] : "3306";
$this->user=!empty($config['user']) ? $config['user'] : "root";
$this->pass=!empty($config['pass']) ? $config['pass'] : "";
$this->char=!empty($config['char']) ? $config['char'] : "utf8";
$this->db=!empty($config['db']) ? $config['db'] : "test";
$link=@mysql_connect("{$config['host']}:{$config['port']}","{$config['user']}","{$config['pass']}");
// mysql_query("set names {$charset}");
// mysql_query("use {$db}");
$this->charset($this->char);
$this->usedb($this->db);
// echo "當前字符編碼爲:".$this->char."數組的字符編碼爲".$config['char'];
}
function charset($charset){ // 設置字符編碼
mysql_query("set names {$charset} ");
}
function usedb($db){ //更改要使用的數據庫
mysql_query("use {$db}");
echo "已切換數據庫 {$db} <br>";
}
function closeDB(){ //關閉數據庫
mysql_close($this->link);
echo "已關閉數據庫連接";
}
function exec($sql){ // 返回增,刪,改語句的返回值爲真假boolen
// $result= mysql_query($chaxun);
// / return print_r($result).'出來了';
// if($result===false){
// // 語句執行失敗,處理失敗 返回錯誤代號
// echo mysql_error($link);
// echo "數據執行失敗";
// exit();
// }else{
// //語句執行成功,返回true
// echo "數據執行成功了";
// return true;
// }
$result=$this->query($sql);
return true; //因爲是增刪改語句,所以直接返回true就行了
}
function getOneRow($sql){ //執行一條返回一行數據的語句,返回一維數組
//result = mysql_query($sql);
// if($result===false){
// echo mysql_error($link);
// echo "數據執行失敗";
// exit();
// }else{
// echo "數據執行成功了";
// return true;
// }
$result =$this->query($sql); // 一行代替幾行代碼
$arr=mysql_fetch_assoc($result);
return $arr;
}
function getRows($sql){ // 執行一條返回多行數據的語句,返回二維數組
// $result = mysql_query($sql);
$result=$this->query($sql);
$array=array();
while ($arr=mysql_fetch_assoc($result)) {
# code...
$array[]=$arr; // 此時就爲二維數組了
}
return $array;
}
function getOnedata($sql){ //執行一條返回一個數據的語句,返回一個直接值
// $result=mysql_query($sql);
//
// if($result===false){
// echo "數據執行失敗";
// echo "請參考如下信息:".mysql_error();
// die();
// }echo "數據執行成功";
$result=$this->query($sql);// 一行代替上面幾行
$arr=mysql_fetch_row($result);
$data=$arr[0]; // 因爲只取出一行,所以直接取出索引爲0的數組即可了
return $data;
}
function query($sql){ // 僅僅用於執行sql語句,然後直接返回sql執行的結果
$result=mysql_query($sql);
if($result===false){
echo "數據執行失敗";
echo "請參考如下信息:".mysql_error();
die();
}echo "數據執行成功";
return $result;
}
}
?>
根據上次的基礎類改進了下,縮短了很多代碼量。下面一個我會把單例模式也加進去,代碼都是可以直接運行的,運行環境是wamp集成環境。
如果有問題可用直接下方留言,作爲PHP中級階層的我(目前大學尚未畢業自學水平)也有很多不熟悉和不懂的地方,如果某些地方做的不太好,歡迎大神前來指正,多多交流!