mysqli扩展库操作mysql数据库
- 配置环境
配置php.ini文件让php支持mysqli扩展库
extension=php_mysqli.dll
- 建库建表
详见博客 “mysql扩展库操作mysql数据库”
- 查询数据库
1 <?php 2 //mysqli扩展库操作mysql数据库,面向对象 3 $mysqli=new MySQLi("localhost","root","root","test"); 4 if($mysqli->connect_error){ 5 die("连接数据库失败".$mysqli->connect_error); 6 } 7 $sql="select * from user1"; 8 $res=$mysqli->query($sql); 9 while($row=$res->fetch_row()){ 10 foreach($row as $key=>$val){ 11 echo "--".$val; 12 } 13 echo "<br/>"; 14 } 15 $res->free(); 16 $mysqli->close(); 17 ?>
结果如下:
- 增删改数据库
1 <?php 2 //mysqli扩展库操作mysql数据库,面向对象 3 $mysqli=new MySQLi("localhost","root","root","test"); 4 if($mysqli->connect_error){ 5 die("连接数据库失败".$mysqli->connect_error); 6 } 7 //$sql="insert into user1 (name,password,age,birthday) values ('wpp',md5('wpp'),25,'1991-05-05')"; 8 //$sql="update user1 set age=24 where name='wpp'"; 9 $sql="delete from user1 where name='wpp'"; 10 $res=$mysqli->query($sql); 11 if(!$res){ 12 echo "操作失败".$mysqli->error; 13 }else{ 14 if($mysqli->affected_rows>0){ 15 echo "操作成功"; 16 }else{ 17 echo "没有行受到影响"; 18 } 19 } 20 $mysqli->close(); 21 ?>
- 把数据库操作封装成类
mysqliTool.class.php 数据库操作文件
1 <?php 2 class MysqliTool{ 3 private $mysqli; 4 private $host="localhost"; 5 private $userName="root"; 6 private $pwd="root"; 7 private $db="test"; 8 public function __construct(){ 9 $this->mysqli=new MySQLi($this->host,$this->userName,$this->pwd,$this->db); 10 if($this->mysqli->connect_error){ 11 die("连接失败".$this->mysqli->connect_error); 12 } 13 $this->mysqli->query("set names utf8"); 14 } 15 public function executeDql($sql){ 16 $res=$this->mysqli->query($sql) or die("操作dql失败".$this->mysqli->error); 17 return $res; 18 } 19 public function executeDml($sql){ 20 $res=$this->mysqli->query($sql); 21 if(!$res){ 22 return 0;//0表示操作失败 23 }else{ 24 if($this->mysqli->affected_rows>0){ 25 return 1;//1表示操作成功 26 }else{ 27 return 2;//2表示没有行受到影响 28 } 29 } 30 } 31 public function mysqliClo(){ 32 $this->mysqli->close(); 33 } 34 } 35 ?>
执行dql语句:
1 <?php 2 //引入类文件 3 require_once "mysqliTool.class.php"; 4 //把类实例化 5 $mysqliTool=new MysqliTool(); 6 //dql语句 7 $sql="select * from user1"; 8 //执行sql语句 9 $res=$mysqliTool->executeDql($sql); 10 while($row=$res->fetch_row()){ 11 foreach($row as $key=>$val){ 12 echo "--".$val; 13 } 14 echo "<br/>"; 15 } 16 $res->free(); 17 $mysqliTool->mysqliClo(); 18 ?>
执行dml语句:
1 <?php 2 //引入类文件 3 require_once "mysqliTool.class.php"; 4 //把类实例化 5 $mysqliTool=new MysqliTool(); 6 //dml语句 7 //$sql="insert into user1 (name,password,age,birthday) values ('wpp',md5('wpp'),25,'1991-05-05')"; 8 //$sql="update user1 set age=24 where name='wpp'"; 9 $sql="delete from user1 where name='wpp'"; 10 //执行sml语句 11 $res=$mysqliTool->executeDql($sql); 12 if($res==0){ 13 echo "操作失败"; 14 }else if($res==1){ 15 echo "操作成功"; 16 }else if($res==2){ 17 echo "没有行受到影响"; 18 } 19 $mysqliTool->mysqliClo(); 20 ?>
posted on 2016-09-28 22:20 seabiscuit0922 阅读(637) 评论(0) 编辑 收藏 举报