2016/3/27 ①连接数据库方法的封装 ②连接数据库 制表 网页查询 奥迪
①连接数据库方法的封装
1 <?php 2 class DBDA 3 { 4 public $host="localhost";//服务器地址 5 public $uid="root";//数据库的用户名 6 public $pwd="123";// 数据库的密码 7 //public $dbname="test2"; 8 //默认要操作的数据库 9 //函数 1 代表查询 10 //执行sql语句,返回相应结果的函数 11 //$sql是要执行的SQL语句 12 //$type是SQL语句的类型,0代表增删改,1代表查询 13 //$db代表要操作的数据库 14 public function Query($sql,$type=1,$db="test2") 15 { 16 //造连接对象 17 $conn=new mysqli($this->host,$this->uid,$this->pwd,$db); 18 19 //判断连接是否成功 20 !mysqli_connect_error()or die("连接失败!"); 21 //执行SQL语句 22 $result=$conn->query($sql); 23 24 //判断SQL语句类型 25 if ($type=1) 26 { //如果是查询语句返回结果集 27 return $result->fetch_all(); 28 } 29 else 30 { //如果是其他语句,返回true或false 31 return $result; 32 } 33 } 34 35 } 36 ?>
②连接数据库后的查询
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 </head> 7 <body> 8 <div> 9 <form action="testchaxun.php" method="post"> 10 <div> 11 <input type="text" name="name"/> 12 <input type="text" name="price"/> 13 <input type="submit" value="查询"/> 14 </div> 15 </form> 16 </div> 17 <table width="100%" cellspacing="0" cellpadding="0" border="1"> 18 <tr> 19 20 <td>代号</td> 21 <td>名称</td> 22 <td>价格</td> 23 </tr> 24 <?php 25 //include 类出现错误 下面代码继续执行 26 //require 出现错误 下面代码不继续执行 27 include("DBDA.php"); 28 $db=new DBDA(); 29 30 @$name=$_POST["name"]; 31 @$price=$_POST["price"]; 32 33 34 $st1=""; 35 $st2=""; 36 if ($name !="") { 37 $st1=" Name like '%{$name}%'"; 38 } 39 else{ 40 $st1=" 1=1"; 41 } 42 if ($price !="") { 43 $st2=" Price = {$price}"; 44 } 45 else{ 46 $st2=" 1=1"; 47 } 48 $str=" where".$st1." and ".$st2; 49 50 //这个方法不好实现 51 // if ($name=="" && $price=="") 52 // { 53 54 // } 55 // else{ 56 // if ($name!="") { 57 // $str=$str." where Name like '%{$name}%'"; 58 // } 59 // if ($Price!="") { 60 61 // } 62 // } 63 // if ($name!="") { 64 // $str=$str." where Name like '%{$name}%'"; 65 // } 66 67 68 //写SQL语句 69 $sql="select Code,Name,Price from Car".$str; 70 echo $sql; 71 //调用类里面的query方法执行sql语句 72 $attr=$db->query($sql); 73 74 for ($i=0; $i < count($attr); $i++) 75 { //关键字变色处理 76 $mc=str_replace($name, "<mark><span style='color:red'>{$name}</span></mark>", $attr[$i][1]); 77 78 //str_replace(search, replace, subject) 79 80 echo "<tr><td>{$attr[$i][0]}</td><td>{$mc}</td><td>{$attr[$i][2]}</td></tr>"; 81 } 82 83 84 85 ?> 86 </table> 87 </body> 88 </html>
显示效果: