用類封裝數據庫連接(unionsql-class.php)
<?php class DBDA { public $host="localhost";//服務器地址 public $uid="root";//用戶名 public $pwd="";//密碼 public $dbconnect;//連接對象 //操作數據庫的方法 //$sql代表需要執行的SQL語句 //$type代表SQL語句的類型,1代表查詢,2代表增刪改 //$dbname代表要操作的數據庫名稱 //如果是查詢,返回二維數組 //如果是增刪改,返回true或false function 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和false return $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; } }
