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();
相關文章
相關標籤/搜索