当前位置:网站首页>PHP Basics - PHP uses PDO
PHP Basics - PHP uses PDO
2022-07-28 08:41:00 【Chon.Wang】
# Preface
List some common PDO Usage method . This article requires you to know some basic
MySQL Add, delete, change and check sentencesknowledge .This article does not deal with any security or authentication , Examples only .
One 、PDO The use of the class
1.1 PHP Use PDO Connect MySQL And create data table
You need to submit and prepare a database by yourself , Article database name : by
test_pdodatabase
# This article does not deal with any security or authentication , Only record the function of each command .
$db_name = 'test_pdo';
$mysql_username = 'root'; # MySQL user name
$mysql_password = 'root'; # MySQL User password
$dsn = "mysql:host=127.0.0.1;dbname=$db_name"; # Host name or host IP
$username = 'Chon';
$password = '123456';
$sex = 'Man';
$time = time();
# 1. establish pdo example , Connect MySQL database
$connect_obj = new PDO($dsn, $username, $password);
# Status code and error reason
if ($connect_obj->errorCode()){
die(" Error code : " . $connect_obj->errorCode . ', Error description : ' . $connect_obj->errorInfo());
}
1.2 perform SQL sentence
# New habits 、 modify 、 Use when deleting
# pdo use exec() Method executes a SQL sentence
# Returns the number of affected rows
# Format : object ->exec($sql_string);
# Used to query , It can also be used to newly added 、 modify 、 Delete
# return PDOStatement object , Return if failed FALSE
# pdo use query() Method executes a SQL Query statement
1.3 Create data table
$create_table_sql = "CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT ' User ID', `user_name` varchar(140) NOT NULL DEFAULT '0' COMMENT ' full name ', `password` varchar(120) NOT NULL COMMENT ' The login password ', `sex` varchar(30) DEFAULT NULL COMMENT ' Gender ', `creattime` varchar(40) NOT NULL COMMENT ' Creation time ', `is_del` enum('YES','NO') DEFAULT 'NO', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT COMMENT=' User table ';";
$create_table_result = $connect_obj->exec($create_table_sql);
1.4 New operation
$insert_sql = "INSERT INTO user (user_name, password, sex, creattime) VALUES ('Leslie','123456','MAN','1658569655')"; # SQL sentence
$insert_result = $connect_obj->exec($insert_sql); # perform SQL sentence
$inseret_id = $connect_obj->lastInsertId(); # Get the autoincrement of newly inserted data ID
1.5 Delete operation
$delete_sql = "DELETE FROM user WHERE id < 5"; # Delete function SQL sentence
$delete_result = $connect_obj->exec($delete_sql); # perform SQL sentence
1.6 Modify the operating
$update_sql = "UPDATE user SET user_name = 'Chon' WHERE id = 6"; # Delete function SQL sentence
$update_result = $connect_obj->exec($update_sql); # perform SQL sentence
1.7 Query operation
# The first one is : Query data - query() Inquire about
# query() The return is PDOStatement object , You need to traverse to get data
$select_all_sql = "SELECT * FROM user where id > 8";
$select_all_result = $connect_obj->query($select_all_sql); # perform SQL sentence
foreach($select_all_result as $val){
# Some data processing
}
Two 、PDOStatement The use of the class
2.1 to 2.3 For preprocessing statements .
2.1 Preparation and execution
# 1. prepare() Prepare to execute SQL sentence , return PDOStatement object
$stmt = $connect_obj->prepare($sql_string);
# 2. execute() Execute the prepared SQL sentence , Return value TRUE | FALSE
$stmt->execute();
2.2 The colon : Placeholders are bound to parameters bindParam() perform
$statement_insert_sql = "INSERT INTO user (user_name, password, sex, creattime) VALUES (:user_name, :password, :sex, :creattime)";
$stmt = $connect_obj->prepare($statement_insert_sql);
# The first way of execution : Pass in an array of parameter values
$result_1 = $stmt->execute([':user_name'=> 'Chon', ':password'=>123456, ':sex'=>'WOMAN', ':creattime'=>time()]);
# The second way of execution : Parameter binding bindParam()
$stmt->bindParam(':user_name', $username);
$stmt->bindParam(':password', $password);
$stmt->bindParam(':sex', $sex);
$stmt->bindParam(':creattime', $time);
$result_2 = $stmt->execute();
2.3 question mark ? Placeholders are bound to parameters bindValue() perform
$statement_insert_sql = "INSERT INTO user (user_name, password, sex, creattime) VALUES (?, ?, ?, ?)";
$stmt = $connect_obj->prepare($statement_insert_sql);
# The first way of execution : In placeholder order , Pass in an array of parameter values
$result_3 = $stmt->execute(['Leslie','123456','MAN','1658569655']);
# The second way of execution : bindValue()
$stmt->bindValue(1, $username);
$stmt->bindValue(2, $password);
$stmt->bindValue(3, $sex);
$stmt->bindValue(4, $time);
$result_4 = $stmt->execute();
2.4 Column binding bindColumn()
# get data
$stmt = $connect_obj->prepare($select_all_sql);
$stmt->execute();
# The first way : Column number binding
$stmt->bindColumn(1, $column_username);
$stmt->bindColumn(2, $column_password);
# The second way : Column name binding
$stmt->bindColumn('sex', $column_sex);
$stmt->bindColumn('creattime', $column_creattime);
# Example :
while ($row = $stmt->fetch()) {
echo $column_username, $column_password, $column_sex, $column_creattime;
}
2.5 Query operation - Get all the data fetchAll()
# get data
$stmt = $connect_obj->prepare($select_all_sql);
$stmt->execute();
$all_result = $stmt->fetchAll(); # Array
2.6 Query operation - Get single line data
# get data
$stmt = $connect_obj->prepare($select_all_sql);
$stmt->execute();
# 1. Object format
while ($row_obj = $stmt->fetchObject()) {
# Some data processing
}
# 2. The array format
# Common parameters : PDO::FETCH_BOTH( Default ), PDO::FETCH_ASSOC( Associative array ), PDO::FETCH_NUM( The index array )
while ($row_array = $stmt->fetch(PDO::FETCH_ASSOC)) {
# Some data processing
}
2.7 Get the number of rows affected rowCount()
$stmt = $connect_obj->prepare($control_sql);
$stmt->execute();
# This method obtains the last SQL The number of lines affected by the execution of the statement
$stmt->rowCount();
3、 ... and 、 The transaction operations
# Business - First step : Open transaction
$connect_obj->beginTransaction();
# Business - The second step : CUD Wait for the operation
$result = "SQL operation ";
# Business - The third step : Commit transaction or roll back transaction
if ($result){
# If the operation results are correct , Then commit the transaction
$connect_obj->commit();
} else {
# If there is an error, rollback the transaction
$connect_obj->rollback();
}
# Other - Check whether it is within a transaction (bool: true | false)
$is_transaction = $connect_obj->inTransaction();
Four 、 The sample code
<?php
# This article does not deal with any security or authentication , Only record the function of each command .
$db_name = 'test_pdo';
$mysql_username = 'root'; # MySQL user name
$mysql_password = 'root'; # MySQL User password
$dsn = "mysql:host=127.0.0.1;dbname=$db_name"; # Host name or host IP
$username = 'Chon';
$password = '123456';
$sex = 'Man';
$time = time();
# One 、PDO The use of the class
## 1.1 establish pdo example , Connect MySQL database
$connect_obj = new PDO($dsn, $mysql_username, $mysql_password);
# Status code and error reason
if ($connect_obj->errorCode()){
die(" Error code : " . $connect_obj->errorCode . ', Error description : ' . $connect_obj->errorInfo());
}
## 1.2 perform MySQL sentence
# exec() New habits 、 modify 、 Use when deleting
# pdo use exec() Method executes a SQL sentence
# Returns the number of affected rows
# Format : object ->exec($sql_string);
# query() Used to query , It can also be used to newly added 、 modify 、 Delete
# return PDOStatement object , Return if failed FALSE
# pdo use query() Method executes a SQL Query statement
## 1.3 Create data table
/* $create_table_sql = "CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT ' User ID', `user_name` varchar(140) NOT NULL DEFAULT '0' COMMENT ' full name ', `password` varchar(120) NOT NULL COMMENT ' The login password ', `sex` varchar(30) DEFAULT NULL COMMENT ' Gender ', `creattime` varchar(40) NOT NULL COMMENT ' Creation time ', `is_del` enum('YES','NO') DEFAULT 'NO', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT COMMENT=' User table ';"; $create_table_result = $connect_obj->exec($create_table_sql); */
## 1.4 New operation
# $insert_sql = "INSERT INTO user (user_name, password, sex, creattime) VALUES ('Leslie','123456','MAN','1658569655')"; # SQL sentence
# $insert_result = $connect_obj->exec($insert_sql); # perform SQL sentence
# $inseret_id = $connect_obj->lastInsertId(); # Get the autoincrement of newly inserted data ID
## 1.5 Delete operation
$delete_sql = "DELETE FROM user WHERE id < 5"; # Delete function SQL sentence
$delete_result = $connect_obj->exec($delete_sql); # perform SQL sentence
## 1.6 Modify the operating
$update_sql = "UPDATE user SET user_name = 'Chon' WHERE id = 6"; # Delete function SQL sentence
$update_result = $connect_obj->exec($update_sql); # perform SQL sentence
## 1.7 Query operation
# The first one is : Query data - query() Inquire about
# query() The return is PDOStatement object , You need to traverse to get data
$select_all_sql = "SELECT * FROM user where id > 8";
$select_all_result = $connect_obj->query($select_all_sql); # perform SQL sentence
foreach($select_all_result as $val){
# Some data processing
}
# Two 、 Preprocessing statement
## 2.1 Preparation and execution
# 1. prepare() Prepare to execute SQL sentence
# $stmt = $connect_obj->prepare($sql_string);
# 2. execute() Execute the prepared SQL sentence , Return value TRUE | FALSE
# $stmt->execute();
## 2.2 The colon (:) Placeholders are bound to parameters bindParam() perform
# $statement_insert_sql = "INSERT INTO user (user_name, password, sex, creattime) VALUES (:user_name, :password, :sex, :creattime)";
# $stmt = $connect_obj->prepare($statement_insert_sql);
# The first way of execution : Pass in an array of parameter values
# $result_1 = $stmt->execute([':user_name'=> 'Chon', ':password'=>123456, ':sex'=>'WOMAN', ':creattime'=>time()]);
# The second way of execution : bindParam()
# $stmt->bindParam(':user_name', $username);
# $stmt->bindParam(':password', $password);
# $stmt->bindParam(':sex', $sex);
# $stmt->bindParam(':creattime', $time);
# $result_2 = $stmt->execute();
## 2.3 question mark (?) Placeholders are bound to parameters bindValue() perform
# $statement_insert_sql = "INSERT INTO user (user_name, password, sex, creattime) VALUES (?, ?, ?, ?)";
# $stmt = $connect_obj->prepare($statement_insert_sql);
# The first way of execution : In placeholder order , Pass in an array of parameter values
# $result_3 = $stmt->execute(['Leslie','123456','MAN','1658569655']);
# The second way of execution : bindValue()
# $stmt->bindValue(1, $username);
# $stmt->bindValue(2, $password);
# $stmt->bindValue(3, $sex);
# $stmt->bindValue(4, $time);
# $result_4 = $stmt->execute();
## 2.4 Column binding bindColumn()
# get data
# $stmt = $connect_obj->prepare($select_all_sql);
# $stmt->execute();
# The first way : Column number binding
# $stmt->bindColumn(1, $column_username);
# $stmt->bindColumn(2, $column_password);
# The second way : Column name binding
# $stmt->bindColumn('sex', $column_sex);
# $stmt->bindColumn('creattime', $column_creattime);
# Example :
#while ($row = $stmt->fetch()) {
# echo $column_username, $column_password, $column_sex, $column_creattime;
#}
# 2.5 Query operation - Get all the data `fetchAll()`
# $stmt = $connect_obj->prepare($select_all_sql);
# $stmt->execute();
# $all_result = $stmt->fetchAll(); # Array
# 2.6 Query operation - Get single line data
$stmt = $connect_obj->prepare($select_all_sql);
$stmt->execute();
# 1. Object format
# while ($row_obj = $stmt->fetchObject()) {
# Some data processing
# }
# 2. The array format
# Common parameters : PDO::FETCH_BOTH( Default ), PDO::FETCH_ASSOC( Associative array ), PDO::FETCH_NUM( The index array )
while ($row_array = $stmt->fetch(PDO::FETCH_ASSOC)) {
# Some data processing
}
# 2.7 Get the number of rows affected
$stmt = $connect_obj->prepare($select_all_sql);
$stmt->execute();
# This method obtains the last SQL The number of lines affected by the execution of the statement
$stmt->rowCount();
# Business - Start
# Business - First step : Open transaction
$connect_obj->beginTransaction();
# Business - The second step : CUD Wait for the operation
$result = "SQL operation ";
# Business - The third step : Commit transaction or roll back transaction
if ($result){
# If the operation results are correct , Then commit the transaction
$connect_obj->commit();
} else {
# If there is an error, rollback the transaction
$connect_obj->rollback();
}
# Other - Check whether it is within a transaction
$is_transaction = $connect_obj->inTransaction();
# Business - end
边栏推荐
猜你喜欢

How to write a JMeter script common to the test team

【MindSpore易点通机器人-01】你也许见过很多知识问答机器人,但这个有点不一样

置顶各大平台,22版面试核心知识解析笔记,强势上榜

思迈特软件完成C轮融资,让BI真正实现“普惠化”

c语言中函数的介绍(血书20000字!!!!)

第2章-14 求整数段和

CAT1 4g+ Ethernet development board 232 data is sent to the server through 4G module TCP

bash-shell 免交互

sql server时间字段排序

2022牛客多校第二场解题报告
随机推荐
Half bridge buck circuit - record
PHP基础知识 - PHP 使用 PDO
NDK 系列(6):说一下注册 JNI 函数的方式和时机
Blog building 7: Hugo
置顶各大平台,22版面试核心知识解析笔记,强势上榜
第2章-2 计算分段函数[1]
Use of tkmapper - super detailed
中标捷报!南大通用GBase 8s中标南瑞集团2022年数据库框架项目
第2章-14 求整数段和
Introduction to self drive tour of snow mountains in the West in January 2018
Recycling of classes loaded by classloader
(十三)基于51单片机的简单温度报警装置
ciou损失
How to use QT help documents
JS手写函数之slice函数(彻底弄懂包头不包尾)
Unity切换到另一个场景的时候,发现该场景变暗了
2022牛客多校第二场解题报告
uniapp上下滑屏切换支持视频和图片轮播实现,类似抖音效果
Usage of qmap
File editing component