韩顺平php 用mysqli扩展库进行CRUD操作(增删改)封装工具类

//封装工具类 sqlHelper.class.php

<?php

class SqlHelper{

private $mysqli;
//将来这里写死的数据信息,是需要配置到一个文件
private static $host="localhost";
private static $user="root";
private static $pwd="root";

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);

}
//设置访问的数据库的字符集
//这句话的作用是保证php是以utf8的方式来操作我们的mysql数据库
$this->mysqli->query("set names utf8");

}
public function execute_dql($sql){

$res=$this->mysqli->query($sql)or die("操作dql".$this->mysqli->error);
return $res;

}
public function execute_dml($sql){

$res=$this->mysqli->query($sql)or die("操作dml".$this->mysqli->error);
if(!$res){
  return 0;//表示成功

}else{
 if($this->mysqli->affected_rows>0){
	 return 1;//表示成功
 
}else{

  return 2;//表示没有行数收到影响

}

}

}

}


?>

操作页面 mysqliDomo1.php

<?php
require_once "SqlHelper.class.php";
//设置编码格式
header("content-type:text/html;charset=utf-8");
//创建SqlHelper对象
$sqlHelper=new SqlHelper();
$sql="insert into user1(name,password,email,age)values('小红帽',md5('aaaa'),'[email protected]',8)";
//通过$sqlHelper对象实例完成添加
$res=$sqlHelper->execute_dml($sql);
if($res==0){
//失败
echo "失败";

}else{
 if($res==1){
  echo "恭喜,成功";
 
 }else if($res==2){
 
 echo "没有行数影响";
 
 }


}

$res=$sqlHelper->execute_dml($sql);
$res=$sqlHelper->execute_dml($sql);
$res=$sqlHelper->execute_dml($sql);
$sql="delete from user1 where id=1";
if($res==1){
 echo "删除成功";

}



?>

猜你喜欢

转载自blog.csdn.net/weixin_43345480/article/details/89708367