Backend Development
PHP Tutorial
PHP database operation class based on pdo [can support mysql, sqlserver and oracle]PHP database operation class based on pdo [can support mysql, sqlserver and oracle]
This article mainly introduces PHP's pdo-based database operation class, which can realize basic database connections, additions, deletions, modifications, and closing connections. It also supports operations on mysql, sqlserver, oracle and other databases. Friends who need it can Refer to the following
The example of this article describes the PHP database operation class based on pdo. Share it with everyone for your reference, the details are as follows:
This class is used when operating sqlserver and oracle at work. At that time, it was improved on the basis of others. Now I will share it
<?php
class Pdodb{
protected $pdo;
protected $res;
protected $config;
/*构造函数*/
function __construct($config){
$this->Config = $config;
$this->connect();
}
/*数据库连接*/
public function connect(){
try {
$this->pdo= new PDO($this->Config['dsn'], $this->Config['username'], $this->Config['password']);//$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$this->pdo->query("set names utf8");
}catch(Exception $e){
echo '数据库连接失败,详情: ' . $e->getMessage () . ' 请在配置文件中数据库连接信息';
exit ();
}
/*
if($this->Config['type']=='oracle'){
$this->pdo->query("set names {$this->Config['charset']};");
}else{
$this->pdo->query("set names {$this->Config['charset']};");
}
*/
//把结果序列化成stdClass
//$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
//自己写代码捕获Exception
//$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);//属性名 属性值 数组以关联数组返回
}
/*数据库关闭*/
public function close(){
$this->pdo = null;
}
//用于有记录结果返回的操作,特别是SELECT操作
public function query($sql,$return=false){
$res = $this->pdo->query($sql);
if($res){
$this->res = $res; // 未返回 return $this->res;
}
if($return){
return $res;
}
}
//主要是针对没有结果集合返回的操作,比如INSERT、UPDATE、DELETE等操作
public function exec($sql,$return=false){
$res = $this->pdo->exec($sql);
if($res){
$this->res = $res;
}
if($return){//返回操作是否成功 成功返回1 失败0
return $res;
}
}
//将$this->res以数组返回(全部返回)
public function fetchAll(){
return $this->res->fetchAll();
}
//将$this->res以数组返回(一条记录)
public function fetch(){
return $this->res->fetch();
}
//返回所有字段
public function fetchColumn(){
return $this->res->fetchColumn();
}
//返回最后插入的id
public function lastInsertId(){
return $this->res->lastInsertId();
}
//返回最后插入的id
public function lastInsertId2(){
return $this->pdo->lastInsertId();
}
/**
* 参数说明
* string/array $table 数据库表,两种传值模式
* 普通模式:
* 'tb_member, tb_money'
* 数组模式:
* array('tb_member', 'tb_money')
* string/array $fields 需要查询的数据库字段,允许为空,默认为查找全部,两种传值模式
* 普通模式:
* 'username, password'
* 数组模式:
* array('username', 'password')
* string/array $sqlwhere 查询条件,允许为空,两种传值模式
* 普通模式(必须加上and,$sqlwhere为空 1=1 正常查询):
* 'and type = 1 and username like "%os%"'
* 数组模式:
* array('type = 1', 'username like "%os%"')
* string $orderby 排序,默认为id倒序
*int $debug 是否开启调试,开启则输出sql语句
* 0 不开启
* 1 开启
* 2 开启并终止程序
* int $mode 返回类型
* 0 返回多条记录
* 1 返回单条记录
* 2 返回行数
*/
public function select($table, $fields="*", $sqlwhere="", $orderby="", $debug=0, $mode=0){
//参数处理
if(is_array($table)){
$table = implode(', ', $table);
}
if(is_array($fields)){
$fields = implode(',',$fields);
/*
if($this->Config['type']=='oracle'){
//$fields = implode(',',$fields);//CUSTOMER_ID,FIRST_NAME,LAST_NAME,EMAIL
//$fields = implode(",'UTF8','ZHS16GBK') ,convert(",$fields);
//$fields="convert(".$fields.",'UTF8','ZHS16GBK')";
}else{
$fields = implode(',',$fields);
}
*/
}
if(is_array($sqlwhere)){
$sqlwhere = ' and '.implode(' and ', $sqlwhere);
}
//数据库操作
if($debug === 0){
if($mode === 2){ //统计
$this->query("select count(*) from $table where 1=1 $sqlwhere");
$return = $this->fetchColumn();
}else if($mode === 1){ //返回一条
$this->query("select $fields from $table where 1=1 $sqlwhere $orderby");
$return = $this->fetch();
}else{
$this->query("select $fields from $table where 1=1 $sqlwhere $orderby");
$return = $this->fetchAll();//如果 $this->res为空即sql语句错误 会提示Call to a member function fetchAll() on a non-object
}
return $return;
}else{
if($mode === 2){
echo "select count(*) from $table where 1=1 $sqlwhere";
}else if($mode === 1){
echo "select $fields from $table where 1=1 $sqlwhere $orderby";
}else{
echo "select $fields from $table where 1=1 $sqlwhere $orderby";
}
if($debug === 2){
exit;
}
}
}
/**
* 参数说明
* string/array $table 数据库表,两种传值模式
* 普通模式:
* 'tb_member, tb_money'
* 数组模式:
* array('tb_member', 'tb_money')
* string/array $set 需要插入的字段及内容,两种传值模式
* 普通模式:
* 'username = "test", type = 1, dt = now()'
* 数组模式:
* array('username = "test"', 'type = 1', 'dt = now()')
* int $debug 是否开启调试,开启则输出sql语句
* 0 不开启
* 1 开启
* 2 开启并终止程序
* int $mode 返回类型
* 0 无返回信息
* 1 返回执行条目数
* 2 返回最后一次插入记录的id
*/
public function oic_insert($table, $set, $debug=0, $mode=0){
//参数处理
if(is_array($table)){
$table = implode(', ', $table);
}
if(is_array($set)){
$s='';$i=0;
foreach($set as $k=>$v){
$i++;
$s[$i]=$k;//,连接
$val[$i]=$v;
}
$sarr=implode(",",$s);//去掉最后一个,
//array_pop($sarr);
$set=implode("','",$val);////15221579236','张三','','2001','8','4','女','是
//$set = implode(', ', $set);
}
//数据库操作
if($debug === 0){
if($mode === 2){
$this->query("insert into $table ($sarr) values('".$set."')");
//$return = $this->lastInsertId();
}else if($mode === 1){
$this->exec("insert into $table ($sarr) values('".$set."')");
$return = $this->res;
}else{
$this->query("insert into $table ($sarr) values('".$set."')");
$return = NULL;
}
return $return;
}else{
echo "insert into $table ($sarr) values('".$set."')";
if($debug === 2){
exit;
}
}
}
public function insert($table, $set, $debug=0, $mode=0){
//参数处理
if(is_array($table)){
$table = implode(', ', $table);
}
if(is_array($set)){
$s='';
foreach($set as $k=>$v){
$s.=$k."='".$v."',";//,连接
}
$sarr=explode(',',$s);//去掉最后一个,
array_pop($sarr);
$set=implode(',',$sarr);
//$set = implode(', ', $set);
}
//数据库操作
if($debug === 0){
if($mode === 2){
$this->query("insert into $table set $set");
$return = $this->pdo->lastInsertId();
}else if($mode === 1){
$this->exec("insert into $table set $set");
$return = $this->res;
}else{
$this->query("insert into $table set $set");
$return = NULL;
}
return $return;
}else{
echo "insert into $table set $set";
if($debug === 2){
exit;
}
}
}
/**
* 参数说明
* string $table 数据库表,两种传值模式
* 普通模式:
* 'tb_member, tb_money'
* 数组模式:
* array('tb_member', 'tb_money')
* string/array $set 需要更新的字段及内容,两种传值模式
* 普通模式:
* 'username = "test", type = 1, dt = now()'
* 数组模式:
* array('username = "test"', 'type = 1', 'dt = now()')
* string/array $sqlwhere 修改条件,允许为空,两种传值模式
* 普通模式:
* 'and type = 1 and username like "%os%"'
* 数组模式:
* array('type = 1', 'username like "%os%"')
* int $debug 是否开启调试,开启则输出sql语句
* 0 不开启
* 1 开启
* 2 开启并终止程序
* int $mode 返回类型
* 0 无返回信息
* 1 返回执行条目数
*/
public function update($table, $set, $sqlwhere="", $debug=0, $mode=0){
//参数处理
if(is_array($table)){
$table = implode(', ', $table);
}
if(is_array($set)){
$s='';
foreach($set as $k=>$v){
$s.=$k."='".$v."',";
}
$sarr=explode(',',$s);//去掉最后一个,
array_pop($sarr);
$set=implode(',',$sarr);
//$set = implode(', ', $set);
}
if(is_array($sqlwhere)){
$sqlwhere = ' and '.implode(' and ', $sqlwhere);
}
//数据库操作
if($debug === 0){
if($mode === 1){
$this->exec("update $table set $set where 1=1 $sqlwhere");
$return = $this->res;
}else{
$this->query("update $table set $set where 1=1 $sqlwhere");
$return = true;
}
return $return;
}else{
echo "update $table set $set where 1=1 $sqlwhere";
if($debug === 2){
exit;
}
}
}
/**
* 参数说明
* string $table 数据库表
* string/array $sqlwhere 删除条件,允许为空,两种传值模式
* 普通模式:
* 'and type = 1 and username like "%os%"'
* 数组模式:
* array('type = 1', 'username like "%os%"')
* int $debug 是否开启调试,开启则输出sql语句
* 0 不开启
* 1 开启
* 2 开启并终止程序
* int $mode 返回类型
* 0 无返回信息
* 1 返回执行条目数
*/
public function delete($table, $sqlwhere="", $debug=0, $mode=0){
//参数处理
if(is_array($sqlwhere)){
$sqlwhere = ' and '.implode(' and ', $sqlwhere); //是字符串需自己加上and
}
//数据库操作
if($debug === 0){
if($mode === 1){
$this->exec("delete from $table where 1=1 $sqlwhere");
$return = $this->res;
}else{
$this->query("delete from $table where 1=1 $sqlwhere");
$return = NULL;
}
return $return;
}else{
echo "delete from $table where 1=1 $sqlwhere";
if($debug === 2){
exit;
}
}
}
}
/*
sqlserver 配置 extension=php_pdo_mssql.dll和extension=php_pdo_sqlsrv.dll 安装对应的 ntwdblib.dll
http://msdn.microsoft.com/en-us/library/cc296170.aspx 下载php版本对应的sqlsrv扩展
sqlserver 配置 odbc连接需开启extension=php_pdo_odbc.dll
*/
$mssql2008_config=array(
'dsn'=>'odbc:Driver={SQL Server};Server=192.168.1.60;Database=his',//数据库服务器地址
'username'=>'sa',
'password'=>'xxxxx',
);
$mssql=new Pdodb($mssql2008_config);
$sql="select * from
(
select row_number()over(order by tempcolumn)temprownumber,*
from (
select top 10 tempcolumn=0,a.*
from DA_GR_HBFS a
where 1=1
) t
) tt
where temprownumber>0";
$mssql->query($sql);
while($res=$mssql->fetch()){
$data[]=$res;
}
print_r($data);exit;
//mysql 操作
$msyql_config=array(
'dsn'=>'mysql:host=localhost;dbname=talk',
'username'=>'root',
'password'=>'123456'
);
$mysql=new PDO_DB($msyql_config);
$sql = 'SELECT user_id, user_name, nickname FROM et_users ';
$mysql->query($sql);
$data=$mysql->fetchAll();
print_r($data);exit;
//oracle 操作
$oci_config=array(
'dsn'=>'oci:dbname=orcl',
'username'=>'BAOCRM',
'password'=>'BAOCRM'
);
$oracle=new PDO_DB($oci_config);
//print_r($oracle);exit;//PDO_DB Object ( [pdo:protected] => PDO Object ( ) [res:protected] => [config:protected] => [Config] => Array ( [dsn] => oci:dbname=orcl [name] => PWACRM [password] => PWACRM ) )
$sql="select * from CUSTOMER_LEVEL t";
$oracle->query($sql);
$data=$oracle->fetchAll();
print_r($data);exit;
/*
Array
(
[0] => Array
(
[LEVEL_ID] => 1
[0] => 1
[LEVEL_NAME] => 普通会员
[1] => 普通会员
[LEVEL_DETAIL] => 普通会员
[2] => 普通会员
[SORT_NUMBER] => 15
[3] => 15
[CREATE_TIME] => 12-7月 -12
[4] => 12-7月 -12
[CREATE_BY] => 1
[5] => 1
[UPDATE_TIME] => 12-7月 -12
[6] => 12-7月 -12
[UPDATE_BY] => 1
[7] => 1
[STATE] => 正常
[8] => 正常
)
)*/
?>
Related recommendations:
MySQL read-write separation operation implemented in PHP
PHP implements the function of preventing repeated form submission (based on token verification)
The above is the detailed content of PHP database operation class based on pdo [can support mysql, sqlserver and oracle]. For more information, please follow other related articles on the PHP Chinese website!
PHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AMPHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.
PHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AMPHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.
Why Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AMThe core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.
Debunking the Myths: Is PHP Really a Dead Language?Apr 16, 2025 am 12:15 AMPHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.
The PHP vs. Python Debate: Which is Better?Apr 16, 2025 am 12:03 AMPHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.
PHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AMPHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.
PHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AMPHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.
How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AMUsing preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 English version
Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment





