PHP封装数据库连接
生活随笔
收集整理的這篇文章主要介紹了
PHP封装数据库连接
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
用類封裝數據庫連接(unionsql-class.php)
<?php class DBDA {public $host="localhost";//服務器地址public $uid="root";//用戶名public $pwd="";//密碼public $dbconnect;//連接對象//操作數據庫的方法//$sql代表需要執行的SQL語句//$type代表SQL語句的類型,1代表查詢,2代表增刪改//$dbname代表要操作的數據庫名稱//如果是查詢,返回二維數組//如果是增刪改,返回true或falsefunction Query($sql,$type=1,$dbname="newssystem"){//造鏈接對象$this->dbconnect=new MySQLi($this->host,$this->uid,$this->pwd,$dbname);//判斷是否出錯if(!mysqli_connect_error()){//如果成功,執行SQL語句$result=$this->dbconnect->query($sql);//根據語句了類型判斷if($type==1){//如果是查詢語句,就返回二維數組return $result->fetch_all(); }else{//如果是其他語句,就返回true和falsereturn $result;}}else{return "鏈接失敗!";}} }其他頁面調用:
$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}')";//沒有定義的不寫,比如前面第一個自增長的 if($db->Query($sql,2)==true)// {header("location:fabuxinwenshouye.php"); } else {echo "注冊失敗"; }用函數封裝數據庫連接(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;} }?
轉載于:https://www.cnblogs.com/panyiquan/p/5587228.html
總結
以上是生活随笔為你收集整理的PHP封装数据库连接的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android OpenCV Manag
- 下一篇: Guice系列之用户指南(五)