mysqli扩展库应用---程序范例

经过mysqli扩展库对用户表user1进行增删改查操做,用户表user1结构以下:php

1,创建数据库操做类库mysqliTool.class.php,代码以下:html

<?php
class mysqliTool{
    private static $host = '127.0.0.1';
    private static $username = 'root';
    private static $password = '123456';
    private static $dbName = 'test';
    private $conn = null;
    private $rs = null;

    public function __construct(){
        $this->conn = new MySQLi(self::$host,self::$username,self::$password,self::$dbName);
        if(!$this->conn){
            die('链接错误:'.$this->conn->connect_error);
        }
        $this->conn->query("set names utf-8");
    }

    public function execute_dql($sql){
        $this->rs = $this->conn->query($sql) or die('查询数据库出错:'.$this->conn->error);
        $rsList = array();
        if($this->rs){
            while($row = $this->rs->fetch_assoc()){
                $rsList[] = $row;
            }
        }
        $this->rs->free();
        return $rsList;
    }

    public function execute_dml($sql){
        $this->rs = $this->conn->query($sql);
        if(!$this->rs){
            $flag = 0;
            die('执行错误:'.$this->conn->error);
        }else if($this->conn->affected_rows >  0){
            $flag =  1;
        }else{
            $flag = 2;
        }
        return $flag;
    }

    public function closeConn(){
        $this->conn->close();
    }
}
?>

  

2,对用户表查询操做,代码页以下:mysql

<?php
require "mysqliTool.class.php";
header("Content-type:text/html;charset=utf-8");
$mysqliTool = new mysqliTool();
$sql = "select * from user1";
$res = $mysqliTool->execute_dql($sql);
while($row = mysqli_fetch_row($res)){
    foreach($row as $key=>$value){
        echo "--$value";
    }
    echo "<br/>";
}
$mysqliTool->closeConn();

  

3,对用户表进行增删改操做,代码页以下:sql

<?php
require "mysqliTool.class.php";
header("Content-type:text/html;charset=utf-8");
$mysqliTool = new mysqliTool();
$sql = "insert into user1 (name,password,email,age) values('小牛',md5('hahaha'),'hahaha@126.com',12)";
$res = $mysqliTool->execute_dml($sql);
if($res == 0){
    echo "运行出错!";
}else {
    if($res == 1){
        echo "运行成功!";
    }else{
        echo "运行成功,可是没有行受到影响!";
    }
}
$mysqliTool->closeConn();
相关文章
相关标签/搜索