封装类
封装类
(1)可以多个地方调用,避免代码的冗余
(2)安全性高
1 <?php 2 class DBDA 3 { 4 public $host = "localhost"; 5 public $uid = "root"; 6 public $pwd = "123"; 7 public $dbname = "test_123"; 8 //执行SQL语句返回相应的结果 9 //$sql 要执行的SQL语句 10 //$type 代表SQL语句的类型,0代表增删改,1代表查询 11 function query($sql,$type=0) 12 { 13 $db = new MySQLi($this->host,$this->uid,$this->pwd,$this->dbname); 14 15 $result = $db->query($sql); 16 17 if($type) 18 { 19 //如果是查询,显示数据 20 return $result->fetch_all(); 21 } 22 else 23 { 24 //如果是增删改,返回true或者false 25 return $result; 26 } 27 } 28 29 //返回字符串的方法 30 public function strquery($sql,$type=1) 31 { 32 $db = new MySQLi($this->host,$this->uid,$this->pwd,$this->dbname); 33 $result = $db->query($sql); 34 $arr = $result->fetch_all(); 35 $str=""; 36 foreach($arr as $v) 37 { 38 $str = $str.implode("^",$v)."|"; 39 } 40 41 $str = substr($str,0,strlen($str)-1); 42 return $str; 43 44 } 45 46 //返回JSON 47 function JSONQuery($sql,$type=1) 48 { 49 $db = new MySQLi($this->host,$this->uid,$this->pwd,$this->dbname); 50 $r = $db->query($sql); 51 52 if($type==1) 53 { 54 return json_encode($r->fetch_all(MYSQLI_ASSOC)); 55 } 56 else 57 { 58 return $r; 59 } 60 } 61 }
应用
1 <body> 2 <select> 3 <?php 4 require "DBDA.class.php";//调用 5 $db = new DBDA(); 6 7 $sql = "select * from nation"; 8 $arr = $db->query($sql); //此处返回的二维数组,不再是结果集 9 10 foreach($arr as $v) 11 { 12 echo "<option value='{$v[0]}'>{$v[1]}</option>"; 13 } 14 15 ?> 16 </select> 17 </body>