當(dāng)前位置:
首頁(yè) >
PHP封装数据库连接
發(fā)布時(shí)間:2025/7/14
59
豆豆
生活随笔
收集整理的這篇文章主要介紹了
PHP封装数据库连接
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
用類封裝數(shù)據(jù)庫(kù)連接(unionsql-class.php)
<?php class DBDA {public $host="localhost";//服務(wù)器地址public $uid="root";//用戶名public $pwd="";//密碼public $dbconnect;//連接對(duì)象//操作數(shù)據(jù)庫(kù)的方法//$sql代表需要執(zhí)行的SQL語(yǔ)句//$type代表SQL語(yǔ)句的類型,1代表查詢,2代表增刪改//$dbname代表要操作的數(shù)據(jù)庫(kù)名稱//如果是查詢,返回二維數(shù)組//如果是增刪改,返回true或falsefunction Query($sql,$type=1,$dbname="newssystem"){//造鏈接對(duì)象$this->dbconnect=new MySQLi($this->host,$this->uid,$this->pwd,$dbname);//判斷是否出錯(cuò)if(!mysqli_connect_error()){//如果成功,執(zhí)行SQL語(yǔ)句$result=$this->dbconnect->query($sql);//根據(jù)語(yǔ)句了類型判斷if($type==1){//如果是查詢語(yǔ)句,就返回二維數(shù)組return $result->fetch_all(); }else{//如果是其他語(yǔ)句,就返回true和falsereturn $result;}}else{return "鏈接失敗!";}} }其他頁(yè)面調(diào)用:
$title=$_POST["title"]; $author=$_POST["author"]; $source=$_POST["source"]; $content=$_POST["content"]; $time=date("Y-m-d H:i:s");include("DBDA.class.php"); $db=new DBDA(); $sql="insert into news values('','{$title}','{$author}','{$source}','{$content}','{$time}')";//沒有定義的不寫,比如前面第一個(gè)自增長(zhǎng)的 if($db->Query($sql,2)==true)// {header("location:fabuxinwenshouye.php"); } else {echo "注冊(cè)失敗"; }用函數(shù)封裝數(shù)據(jù)庫(kù)連接(unionsql-function.php)
function unionsql($sql,$host='localhost',$usename='root',$password='',$mysql='index') {$db=new MySQLi($host,$usename,$password,$mysql);!mysqli_connect_error() or die('連接失敗');$result=$db->query($sql);$sql=ltrim($sql," ");$str=substr($sql,0,6);$type=1;if($str=='select'){$type=0;}if($type==0){return $result->fetch_all();}else{return $result;} }?
轉(zhuǎn)載于:https://www.cnblogs.com/panyiquan/p/5587228.html
總結(jié)
以上是生活随笔為你收集整理的PHP封装数据库连接的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android OpenCV Manag
- 下一篇: [php-src]扩展中封装业务与 ca