PHP面向对象mysqli增删改查工具类实现
本内容分享了利用PHP实现的、基于面向对象思想的mysqli扩展库增删改查操作工具类。该方案旨在为开发者提供参考范例,便于在实际项目中应用。
相较于传统的mysql扩展库,mysqli扩展库进行了全面优化,有效增强了系统稳定性与执行效率。它包含面向过程和面向对象两种编程风格,其中面向对象方式更为常用。其基本操作逻辑与传统mysql扩展库相似,本文将重点展示如何抽取并封装通用的MySQL操作工具类及调用类。
首先介绍mysqli扩展库操作数据库的核心工具类实现细节。
<?php
//数据库操作类
class DBUtil{
private $host="localhost";
private $username="root";
private $password="123456";
private $dbname="student";
private $conn;
public function DBUtil(){
$this->conn=new mysqli($this->host, $this->username, $this->password,$this->dbname) or die($this->conn->connect_error);
}
//查询
public function query($sql){
$all= $this->conn->query($sql);
return $all;
}
//插入,修改,删除
public function otherOperate($sql){
if($this->conn->query($sql)){
if($this->conn->affected_rows>0){
return "OK";
}else{
return "ERROOR";
}
}
}
public function close(){
$this->conn->close();
}
}
?>
接下来展示具体调用上述工具类的完整代码示例。
<?php
require_once "MySQLUtil.php";
/*$sql="select * from m_student";
$util=new DBUtil();
$result=$util->query($sql);
while($row=$result->fetch_assoc()){
echo "$row[stuName]"."</br>";
}
$result->free();
$util->close();*/
$sql="update m_student set stuName='杨幂' where id=3";
$util=new DBUtil();
$result=$util->otherOperate($sql);
echo $result;
$util->close();
?>
若需使用其他未涵盖的方法,建议查阅官方PHP开发文档获取详细支持。
期望上述关于PHP程序设计的分享能为大家提供实质性的帮助。