Backend Development
PHP Tutorial
Detailed tutorials and practical demonstrations on connecting to the database with PDO in PHPDetailed tutorials and practical demonstrations on connecting to the database with PDO in PHP
PDO—Database Abstraction Layer
Introduction: The PDO extension defines a lightweight, consistent interface for PHP to access the database. PDO solves the problem of inconsistent database connections.
1. Introduction to PDO
This chapter mainly introduces the installation and configuration of PDO, and how to use PDO to connect to the database.
1-1 Introduction to PDO
PDO is the abbreviation of PHP Data Object. It is released together with PHP5.1 version and currently supports databases. Includes Firebird, FreeTDS, Interbase, MySQL, MS SQL Server, ODBC, Oracle, Postgre SQL, SQLite and Sybase. When operating different databases, you only need to modify the DSN (database source) in PDO to operate using the unified interface of PDO.
PDO Features:
Coding Consistency: PDO provides a single interface that can be used with various databases
Flexibility: PDO must be loaded at runtime Database driver, so there is no need to reconfigure and recompile PHP every time you use the database
High performance: PDO is written in C language and compiled into PHP. Compared with other solutions written in PHP, Although other functions are the same, it provides higher performance
Object-oriented features: PDO uses the object-oriented features of PHP5 to achieve more efficient database communication.
Note: PDO extension is just an abstract interface layer. Using PDO extension itself cannot realize any database operation. You must use a characteristic form to express their respective characteristics.

##1-2 PDO configuration and activation

#1-3 PDO connection database

//通过参数形式连接数据库
try{
$dsn='mysql:host=localhost;dbname=school';
$username='root';
$password='root';
$pdo=new PDO($dsn,$username,$password);
var_dump($pdo);
}catch (PDOException $e){
echo $e->getMessage();
};
需要注意:dsn是你的数据源
输出结果:object(PDO)#1 (0) { }
2. Use of PDO objects 主要介绍PDO对象方法的使用。 2-1 [PDO] exec()方法执行建表操作 输出结果:int(0); 2-2 [PDO] exec()方法执行插入记录操作 续上面:插入一条或多条记录 2-3 [PDO] exec()方法执行其他SQL操作 本身是king,修改为king,会是0条记录被影响. lastInsertId() 只能对插入有影响。 exec()对查询无作用 2-4 [PDO] errorCode()和errorInfo()方法查看错误信息 2-5 [PDO] query()方法执行查询语句 注意:更多的用query()查询数据,用exec()实现增删改 2-6 [PDO] prepare()和execute()方法执行查询语句 指定类型:我们更多的是想得到关联数组,我们可以通过两种方式来获得,第一种方式:设置其取回数据的方式(设置参数、常量);第二种方式:通过方法 三、 PDOStatement对象的使用 本章主要介绍PDOStatement对象方法的使用,以及参数的绑定与预处识。 3-1 [PDO] quote()方法防止SQL注入 带条件查询 登录实现的例子 3-2 [PDO] 预处理语句中的占位符的使用 3-3 [PDO] bindParam()方法绑定参数 两种方式:命名参数占位符,问号方式 3-4 [PDO] bindValue()方法绑定参数 向用户表插入数据:命名参数占位符,问号方式类似 3-5 [PDO] bindColumn()方法绑定参数 3-6 [PDO] fetchColumn()方法从结果集中返回一列 3-7 [PDO] debugDumpParams()方法打印一条预处理语句 四、PDO事务处理 主要介绍如何使用PDO进行事务处理 4-1 PDO错误处理模式 3种错误处理模式 4-2 PDO事务处理 好了,以上就是关于本文介绍的关于PHP中PDO操作数据库的详细操作以及实例了,相了解更多相关问题请访问PHP中文网:

<?php
try{
//驱动器的名称 mysql
$pdo=new PDO('mysql:host=localhost;dbname=school','root','root');
//exec():执行一条sql语句并返回其受影响的行数;如果没有受影响的记录,它返回0
//exec对于select没有作用
//PHP是一个Web编程语言,在编程过程中难免会遇到用echo来输出大段的html和javascript脚本的情况,
//如果用传统的输出方法 ——按字符串输出的话,
//肯定要有大量的转义符来对字符串中的引号等特殊字符进行转义,以免出现语法错误。
//如果是一两处还可以容忍,但是要是一个完整的 html文本或者是一个200行的js我想是谁都会崩溃的。
//这就是PHP为什么要引入一个定界符的原因——至少一大部分原因是这样的。
/* 1.PHP定界符的作用就是按照原样,包括换行格式什么的,输出在其内部的东西;
2.在PHP定界符中的任何特殊字符都不需要转义;
3.PHP定界符中的PHP变量会被正常的用其值来替换。
PHP中的定界符格式是这样的:
<<<Eof
……
Eof;*/
$sql=<<<EOF
create table if not exists t_teacher(
id int UNSIGNED auto_increment primary key,
teaname varchar(20) not null UNIQUE,
pwd char(32) not null,
email varchar(30) not null
);
EOF;
$res= $pdo->exec($sql);
var_dump($res);
}catch (PDOException $e){
echo $e->getMessage();
};<?php
try{
//驱动器的名称 mysql
$pdo=new PDO('mysql:host=localhost;dbname=school','root','root');
$sql='insert into t_teacher values(default,"king5","'.md5('king').'","waly@qq.com");';
$res=$pdo->exec($sql);
echo $res;
}catch (PDOException $e){
echo $e->getMessage();
};<?php
try{
//驱动器的名称 mysql
$pdo=new PDO('mysql:host=localhost;dbname=school','root','root');
//$sql='insert into t_teacher values(default,"king6","'.md5('king').'","waly@qq.com");';
$sql=<<<EOF
insert into t_teacher values
(default,"king7","'.md5('king').'","waly@qq.com"),
(default,"king8","'.md5('king').'","waly@qq.com"),
(default,"king9","'.md5('king').'","waly@qq.com")
EOF;
$res=$pdo->exec($sql);
echo '受影响的记录的条数为:'. $res."<br/>";
//$pdo->lastInsertId():得到新插入记录的ID号
//echo '最后插入的ID号为:'.$pdo->lastInsertId();
}catch (PDOException $e){
echo $e->getMessage();
};
<?php
try{
//驱动器的名称 mysql
$pdo=new PDO('mysql:host=localhost;dbname=school','root','root');
//错误的表名
$sql='insert into t_teacher1 values(default,"king6","'.md5('king').'","waly@qq.com");';
$res=$pdo->exec($sql);
if($res===false){
//$pdo->errorCode(); SQLSTATE的值
echo $pdo->errorCode();
echo '<hr/>';
//$pdo->errorInfo():返回的错误信息的数组,数组中包含3个单元
//0=>SQLSTATE(错误编号),1=>CODE(错误码),2=>INFO(错误信息)
$errInfo=$pdo->errorInfo();
print_r($errInfo);
}
}catch (PDOException $e){
echo $e->getMessage();
};<?php
try{
//驱动器的名称 mysql
$pdo=new PDO('mysql:host=localhost;dbname=school','root','root');
//查询一条记录
//$sql='select * from t_teacher where id=5';
//查询多条记录
$sql='select * from t_teacher';
//$pdo->query($sql):执行sql语句,返回PDOStatement对象:需要遍历这个对象,将里面的内容取出来
$stmt=$pdo->query($sql);
var_dump($stmt); //只能看出这个语句返回的是一个对象
echo '<hr/>';
foreach ($stmt as $row){
print_r($row);
echo '<hr/>';
echo '编号:'.$row['id'].'<br/>';
echo '用户名:'.$row['teaname'].'<br/>';
echo '邮箱:'.$row['email'].'<br/>';
echo '<hr/>';
}
}catch (PDOException $e){
echo $e->getMessage();
};Query()用于插入数据
<?php
try{
//驱动器的名称 mysql
$pdo=new PDO('mysql:host=localhost;dbname=school','root','root');
//插入一条记录
$sql='insert into t_teacher values(default,"king12","'.md5('king').'","waly@qq.com");';
//$pdo->query($sql):执行sql语句,返回PDOStatement对象:需要遍历这个对象,将里面的内容取出来
$stmt=$pdo->query($sql);
var_dump($stmt); //只能看出这个语句返回的是一个对象
}catch (PDOException $e){
echo $e->getMessage();
};
<?php
//查询单条语句
try{
//驱动器的名称 mysql
$pdo=new PDO('mysql:host=localhost;dbname=school','root','root');
//查询一条记录
$sql='select * from t_teacher where id=5';
//$pdo->prepare($sql);准备sql语句
$stmt=$pdo->prepare($sql);
//execute():执行预处理语句
$res=$stmt->execute();
//var_dump($res); //会返回bool(true)
//查数据使用
//fetch():得到结果集中的一条记录(作为索引+关联样式返回)
$row=$stmt->fetch();
print_r($row);
}catch (PDOException $e){
echo $e->getMessage();
};<?php
try{
//驱动器的名称 mysql
$pdo=new PDO('mysql:host=localhost;dbname=school','root','root');
//查询多条记录
$sql='select * from t_teacher';
//$pdo->prepare($sql);准备sql语句
$stmt=$pdo->prepare($sql);
//execute():执行预处理语句
$res=$stmt->execute();
//var_dump($res); //会返回bool(true)
//查数据使用
//fetch():得到结果集中的一条记录(作为索引+关联数组)
/*if($res){
while ($row=$stmt->fetch()){
print_r($row);
echo '<hr/>';
}
}*/
//fetchAll() 查询所有记录,以二维数组(索引+关联方式)
$rows=$stmt->fetchAll();
print_r($rows);
}catch (PDOException $e){
echo $e->getMessage();
};
<?php
header('content-type:text/html;charset=utf-8');
$username=$_POST['username'];
$password=$_POST['password'];
try{
//连接数据库
$pdo=new PDO('mysql:host=localhost;dbname=school','root','root');
//向数据库表查找对应的用户信息//如果存在,证明有这个用户,登录成功;否则登录失败
//输入 'or 1=1 # 可以查看查到的数据
//$sql="select * from t_user WHERE `name`='{$username}' AND `password`='{$password}'"; //通过quote():返回带引号的字符串,过滤字符串中的特殊字符
$username=$pdo->quote($username);
$sql="select * from t_user WHERE `name`={$username} AND `password`={$password}";
echo $sql;
$stmt=$pdo->query($sql);
//PDOStatement对象的方法:rowCount() :对于select操作返回的结果集中记录的条数,
//对于INSERT、UPDATE、DELETE返回受影响的记录的条数
echo $stmt->rowCount();
}catch (PDOException $e){
echo $e->getMessage();
}<?php
header('content-type:text/html;charset=utf-8');
$username=$_POST['username'];
$password=$_POST['password'];
try{
//连接数据库
$pdo=new PDO('mysql:host=localhost;dbname=school','root','root');
//占位符有两种方法
//第一种方法
$sql="select * from t_user WHERE `name`=:username and `password`=:password";
$stmt=$pdo->prepare($sql);
$stmt->execute(array(":username"=>$username,":password"=>$password));
//PDOStatement对象的方法:rowCount() :对于select操作返回的结果集中记录的条数,
//对于INSERT、UPDATE、DELETE返回受影响的记录的条数
echo $stmt->rowCount();
//第二种方法
$sql="select * from t_user WHERE `name`=? and `password`=?";
$stmt=$pdo->prepare($sql);
$stmt->execute(array($username,$password));
echo $stmt->rowCount();
}catch (PDOException $e){
echo $e->getMessage();
}<?php
header('content-type:text/html;charset=utf-8');
try{
//连接数据库
$pdo=new PDO('mysql:host=localhost;dbname=school','root','root');
// $sql="insert into t_user(`name`,`password`,`sex`) VALUES (:username,:password,:sex)";
$sql="insert into t_user VALUES (DEFAULT ,:username,:password,:sex)";
$stmt=$pdo->prepare($sql);
$stmt->bindParam(":username",$username,PDO::PARAM_STR);
$stmt->bindParam(":password",$password,PDO::PARAM_STR);
$stmt->bindParam(":sex",$sex,PDO::PARAM_STR);
$username='张三';
$password='123654';
$sex='M';
$stmt->execute();
echo $stmt->rowCount();
}catch (PDOException $e){
echo $e->getMessage();
}<?php
header('content-type:text/html;charset=utf-8');
try{
//连接数据库
$pdo=new PDO('mysql:host=localhost;dbname=school','root','root');
// $sql="insert into t_user(`name`,`password`,`sex`) VALUES (:username,:password,:sex)";
$sql="insert into t_user VALUES (DEFAULT ,?,?,?)";
$stmt=$pdo->prepare($sql);
$stmt->bindParam(1,$username);
$stmt->bindParam(2,$password);
$stmt->bindParam(3,$sex);
$username='张三1';
$password='1236541';
$sex='F';
$stmt->execute();
echo $stmt->rowCount();
}catch (PDOException $e){
echo $e->getMessage();
}<?php
header('content-type:text/html;charset=utf-8');
try{
//连接数据库
$pdo=new PDO('mysql:host=localhost;dbname=school','root','root');
// $sql="insert into t_user(`name`,`password`,`sex`) VALUES (:username,:password,:sex)";
$sql="insert into t_user VALUES (DEFAULT ,?,?,?)";
$stmt=$pdo->prepare($sql);
$username='李四';
$password='123654';
$stmt->bindValue(1,$username);
$stmt->bindValue(2,$password);
$stmt->bindValue(3,'M');
$stmt->execute();
echo $stmt->rowCount();
$username='李四1';
$password='1236541';
$stmt->bindValue(1,$username);
$stmt->bindValue(2,$password);
$stmt->bindValue(3,'M');
$stmt->execute();
echo $stmt->rowCount();
}catch (PDOException $e){
echo $e->getMessage();
}
<?php
header('content-type:text/html;charset=utf-8');
try{
//连接数据库
$pdo=new PDO('mysql:host=localhost;dbname=school','root','root');
// $sql="insert into t_user(`name`,`password`,`sex`) VALUES (:username,:password,:sex)";
$sql="select `name`,`password`,`sex` from t_user";
$stmt=$pdo->prepare($sql);
$stmt->execute();
echo '结果集中的列数一共有:'.$stmt->columnCount();
echo "<hr/>";
print_r($stmt->getColumnMeta(0));
$stmt->bindColumn(1,$username);
$stmt->bindColumn(2,$password);
$stmt->bindColumn(3,$sex);
while ($stmt->fetch(PDO::FETCH_BOUND)){
echo '用户名:'.$username."-密码:".$password."-性别:".$sex."<hr/>";
}
echo $stmt->rowCount();
}catch (PDOException $e){
echo $e->getMessage();
}<?php
header('content-type:text/html;charset=utf-8');
try{
//连接数据库
$pdo=new PDO('mysql:host=localhost;dbname=school','root','root'); $sql="select `name`,`password`,`sex` from t_user";
$stmt=$pdo->query($sql);
//索引默认从0开始
echo $stmt->fetchColumn(0),"<br/>";
echo $stmt->fetchColumn(1),"<br/>";
echo $stmt->fetchColumn(2);
}catch (PDOException $e){
echo $e->getMessage();
}<?php
header('content-type:text/html;charset=utf-8');
try{
//连接数据库
$pdo=new PDO('mysql:host=localhost;dbname=school','root','root');
// $sql="insert into t_user(`name`,`password`,`sex`) VALUES (:username,:password,:sex)";
$sql="insert into t_user VALUES (DEFAULT ,:username,:password,:sex)";
$stmt=$pdo->prepare($sql);
$stmt->bindParam(":username",$username,PDO::PARAM_STR);
$stmt->bindParam(":password",$password,PDO::PARAM_STR);
$stmt->bindParam(":sex",$sex,PDO::PARAM_STR);
$username='张三';
$password='123654';
$sex='M';
$stmt->execute();
$stmt->debugDumpParams();
}catch (PDOException $e){
echo $e->getMessage();
}静默模式
<?php
header('content-type:text/html;charset=utf-8');
/*PDO::ERRMODE_SLIENT:默认模式,静默模式*/
try{
//连接数据库
$pdo=new PDO('mysql:host=localhost;dbname=school','root','root');
$sql="select * from nonet_user";
$stmt=$pdo->query($sql);
echo $pdo->errorCode();
echo '<br/>';
echo $pdo->errorInfo();
}catch (PDOException $e){
echo $e->getMessage();
}<?php
header('content-type:text/html;charset=utf-8');
/*PDO::ERRMODE_SLIENT:默认模式,静默模式
*PDO::ERRMODE_WARNING:警告模式
* PDO::ERRMODE_EXCEPTION:异常模式
*/
try{
//连接数据库
$pdo=new PDO('mysql:host=localhost;dbname=school','root','root');
//设置警告模式
//$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);
//设置异常模式:推荐使用
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$sql="select * from nonet_user";
$stmt=$pdo->query($sql);
echo $pdo->errorCode();
echo '<br/>';
echo $pdo->errorInfo();
}catch (PDOException $e){
echo $e->getMessage();
}
<?php
header('content-type:text/html;charset=utf-8');
try{
$option=array(PDO::ATTR_AUTOCOMMIT,0);
$pdo=new PDO('mysql:host=localhost;dbname=school','root','root',$option);
//开启事务
$pdo->beginTransaction();
var_dump($pdo->inTransaction());
$sql="update account set money=money-200 WHERE username='king'";
$res=$pdo->exec($sql);
if($res==0){
throw new PDOException('转账失败');
}
$res1=$pdo->exec('update account set money=money+200 WHERE username="queen"');
if($res1==0){
throw new PDOException('接收失败');
}
$pdo->commit();
}catch (PDOException $e){
$pdo->rollBack();
echo $e->getMessage();
}
The above is the detailed content of Detailed tutorials and practical demonstrations on connecting to the database with PDO in PHP. For more information, please follow other related articles on the PHP Chinese website!
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.
PHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AMPHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
PHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AMPHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.
PHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AMPHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.
PHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AMPHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.
The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AMPHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.


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

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

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Atom editor mac version download
The most popular open source editor

Dreamweaver CS6
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function





