本文章来给各位同学介绍在php中的两种数据库操作对比,我们常用的是mysql但php学可以支持mysqli,下面我来给大家介绍他们两的一些用法与比较.
1、在PHP中 使用mysqli扩展库对mysql 的dql操作,代码如下:
- <?php
-
- header("Content-type: text/html;charset=utf-8");
-
-
-
-
- $mysqli =new MySQLi("localhost","root","root","test");
- if($mysqli->connect_error){
- die("连接失败".$mysqli->connect_error);
- }
-
-
- $sql="select *from user1";
-
-
- $res =$mysqli->query($sql);
-
-
- while($row=$res->fetch_row()){
-
- var_dump($row);
-
-
-
-
-
- }
-
- $res->free();
- $mysqli->close();
- ?>
下面是面向过程的,代码如下:
- <?php
-
- header("Content-type: text/html;charset=utf-8");
-
- $mysqli=mysqli_connect("localhost","root","root","test");
- if(!$mysqli){
- die("连接失败".mysqli_connect_error());
- }
-
- $sql="select *from user1";
-
- $res=mysqli_query($mysqli,$sql);
-
-
- while($row=mysqli_fetch_row($res)){
-
- foreach ($row as $val){
-
- echo '-'.$val;
- }
- echo '<br/>';
- }
-
-
- mysqli_free_result($res);
- mysqli_close($mysqli);
- ?>
2、在PHP中 使用mysqli扩展库对mysql 的dml操作,代码如下:
- <?php
-
-
- header("Content-type: text/html;charset=utf-8");
- $mysqli = new MySQLi("localhost","root","root","test");
-
- if($mysqli->connect_error){
- die("连接失败".$mysql->connect_error);
- }
-
-
-
-
-
-
- $sql="update user1 set age=20 where id=7";
-
- $res=$mysqli->query($sql);
- if(!$res){
- echo "操作失败".$mysqli->error;
- }else{
- if($mysqli->affected_rows>0){
- echo "成功";
- }else{
- echo "没有行受影响";
- }
- }
-
-
- $mysqli->close();
- ?>
3、进行封装,代码如下:
- <?php
-
- class SqlHelper{
-
- private $mysqli;
-
- private static $host="localhost";
- private static $user="root";
- private static $pwd="root";
- private static $db="test";
-
- public function __construct(){
-
- $this->mysqli=new MySQLi(self::$host,self::$user,self::$pwd,self::$db);
- if($this->mysqli->connect_error){
- die("连接失败".$this->mysqli->connect_error);
- }
-
- $this->mysqli->query("set names utf8");
- }
-
-
- function execute_dql($sql){
-
- $res =$this->mysqli->query($sql) or die($this->mysqli->error);
- return $res;
- }
-
-
- function execute_dml($sql){
-
- $res =$this->mysqli->query($sql) or die($this->mysqli->error);
-
- if(!$res){
- return 0;
- }else{
- if($this->mysqli->affected_rows>0){
- return 1;
- }else{
- return 2;
- }
- }
- }
- }
- ?>
|