mysqli扩展库应用---程序范例
通过mysqli扩展库对用户表user1进行增删改查操作,用户表user1结构如下:

1,建立数据库操作类库mysqliTool.class.php,代码如下:
<?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,对用户表查询操作,代码页如下:
<?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,对用户表进行增删改操作,代码页如下:
<?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();
浙公网安备 33010602011771号