Home >Backend Development >PHP Tutorial >PHP e-commerce shopping cart (2: encapsulating database operation class)
(Refer to the Mypdo written by the self-paid teacher, and attach a PDO summary after this article. in the learning summary module).
<?php
/**
* 自己封装的Pdo操作类
* User: hangfu
* Date: 2016-6-24
* Time: 16:36
* version: 1.0.0.1
*/
class MyPdo{
/**
* @var Pdo 私有的PDO对象
*/
private $pdo;
/**
* 构造方法,用于初始化PDO对象
*/
public function __construct(){
rrree Configuration file (in the same directory file as the current class file) if(file_exists(_DIR_.'db.ini')){
$ini = parse_ini_file('db.ini');
$dsn = $ini['db'].":host=".$ini['host'].";dbname=".$ini['dbname'].";port=".$ini['host']
.";charset=".$ini['charset'];
}else{
die('配置文件不存在....');
}
$this->pdo = new PDO($dsn, $ini['username'], $ini['userpwd']);
}
/**
* 析构方法,用于销毁时同时销毁PDO对象
*/
public function __destruct(){
if($this->pdo)
$this->pdo = null;
}
/**
* 接收SQL(DML)语句并执行返回受影响的行数
* @param $sql 传入的sql语句字符串
*/
public function pdoExec($sql){
return $this->pdo->exec($sql);
}
/**
* 接收SQL(DQL)语句,该语句不带参数,执行并返回查询结果,返回的值为二维数组;如果没有结果,返回null
* @param $sql 传入的sql语句字符串
*/
public function pdoQuery($sql){
$data = $this->pdo->query($sql);
if($data){
return $data->fetchAll(PDO::FETCH_NUM);
}else{
return null;
}
}
/**
* 接收SQL(DQL)语句,该语句不带参数,执行并返回查询结果,返回的值为二维数组;如果没有结果,返回null
* @param $sql 传入的sql语句字符串
* @param $objname 传入的对象名称,字符串格式
*/
public function pdoQueryByObj($sql, $objname){
$data = $this->pdo->query($sql);
if($data){
$datalist = array();
while($info=$data->fetchObject($objname)){
array_push($datalist, $info);
}
return $datalist;
}else{
return null;
}
}
/**
* 接收SQL(DQL)语句,该语句带参数,执行并返回查询结果,返回的值为二维数组;如果没有结果,返回null
* @param $sql 传入的sql语句字符串
* @param $arr 传入的参数值,数组格式
*/
public function pdoPrepare($sql, $arr){
$data = $this->pdo->prepare($sql);
$bl = $data->execute($arr);
if($bl){
return $data->fetchAll(PDO::FETCH_NUM);
}else{
return null;
}
}
/**
* 接收SQL(DQL)语句,该语句不带参数,执行并返回查询结果,返回的值为二维数组;如果没有结果,返回null
* @param $sql 传入的sql语句字符串
* @param $objname 传入的对象名称,字符串格式
* @param $arr 传入的参数值,数组格式
*/
public function pdoPrepareByObj($sql, $objname, $arr){
$data = $this->pdo->prepare($sql);
$bl = $data->execute($arr);
if($bl){
$datalist = array();
while($info=$data->fetchObject($objname)){
array_push($datalist, $info);
}
return $datalist;
}else{
return null;
}
}
}
###数据库类型 db=mysql ###数据库名称 dbname=phpwork ###服务器地址或名称 host=localhost ###数据库字符集 charset=utf8 ###数据库端口号 port=3306 ###操作的用户名 username=xuzhengyang ###操作的用户密码 userpwd=rrree configuration file (in the same directory file as the current class file) rrreee
The above has introduced the PHP e-commerce shopping cart (Part 2: Encapsulating database operation class), including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.