Home > Backend Development > PHP Tutorial > Detailed tutorials and practical demonstrations on connecting to the database with PDO in PHP

Detailed tutorials and practical demonstrations on connecting to the database with PDO in PHP

王林
Release: 2023-04-07 10:36:01
forward
3883 people have browsed it

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.

Detailed tutorials and practical demonstrations on connecting to the database with PDO in PHP

##1-2 PDO configuration and activation

Detailed tutorials and practical demonstrations on connecting to the database with PDO in PHP

#1-3 PDO connection database

Detailed tutorials and practical demonstrations on connecting to the database with PDO in PHP

1. Connect to the database through parameter form (focus on mastering this method)

//通过参数形式连接数据库
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) { }
Copy after login

2. Use of PDO objects

主要介绍PDO对象方法的使用。

2-1 [PDO] exec()方法执行建表操作 Detailed tutorials and practical demonstrations on connecting to the database with PDO in PHP

Detailed tutorials and practical demonstrations on connecting to the database with PDO in PHP

<?php
try{
    //驱动器的名称 mysql
    $pdo=new PDO(&#39;mysql:host=localhost;dbname=school&#39;,&#39;root&#39;,&#39;root&#39;);
    //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();
};
Copy after login

输出结果:int(0);

2-2 [PDO] exec()方法执行插入记录操作

续上面:插入一条或多条记录

<?php
try{
    //驱动器的名称 mysql
    $pdo=new PDO(&#39;mysql:host=localhost;dbname=school&#39;,&#39;root&#39;,&#39;root&#39;);
    $sql=&#39;insert into t_teacher values(default,"king5","&#39;.md5(&#39;king&#39;).&#39;","waly@qq.com");&#39;;
    $res=$pdo->exec($sql);
    echo $res;
}catch (PDOException $e){
    echo $e->getMessage();
};
Copy after login
<?php
try{
    //驱动器的名称 mysql
    $pdo=new PDO(&#39;mysql:host=localhost;dbname=school&#39;,&#39;root&#39;,&#39;root&#39;);
    //$sql=&#39;insert into t_teacher values(default,"king6","&#39;.md5(&#39;king&#39;).&#39;","waly@qq.com");&#39;;
   $sql=<<<EOF
      insert into t_teacher values
      (default,"king7","&#39;.md5(&#39;king&#39;).&#39;","waly@qq.com"),
      (default,"king8","&#39;.md5(&#39;king&#39;).&#39;","waly@qq.com"),
      (default,"king9","&#39;.md5(&#39;king&#39;).&#39;","waly@qq.com")
EOF;

    $res=$pdo->exec($sql);
    echo &#39;受影响的记录的条数为:&#39;. $res."<br/>";
    //$pdo->lastInsertId():得到新插入记录的ID号
    //echo &#39;最后插入的ID号为:&#39;.$pdo->lastInsertId();
}catch (PDOException $e){
    echo $e->getMessage();
};
Copy after login

2-3 [PDO] exec()方法执行其他SQL操作

Detailed tutorials and practical demonstrations on connecting to the database with PDO in PHP

本身是king,修改为king,会是0条记录被影响.

lastInsertId() 只能对插入有影响。

exec()对查询无作用

2-4 [PDO] errorCode()和errorInfo()方法查看错误信息

<?php
try{
    //驱动器的名称 mysql
    $pdo=new PDO(&#39;mysql:host=localhost;dbname=school&#39;,&#39;root&#39;,&#39;root&#39;);
   //错误的表名
    $sql=&#39;insert into t_teacher1 values(default,"king6","&#39;.md5(&#39;king&#39;).&#39;","waly@qq.com");&#39;;
    $res=$pdo->exec($sql);
    if($res===false){
        //$pdo->errorCode(); SQLSTATE的值
        echo $pdo->errorCode();
        echo &#39;<hr/>&#39;;
      //$pdo->errorInfo():返回的错误信息的数组,数组中包含3个单元
     //0=>SQLSTATE(错误编号),1=>CODE(错误码),2=>INFO(错误信息)
        $errInfo=$pdo->errorInfo();
        print_r($errInfo);
    }
}catch (PDOException $e){
    echo $e->getMessage();
};
Copy after login

2-5 [PDO] query()方法执行查询语句

<?php
try{
    //驱动器的名称 mysql
    $pdo=new PDO(&#39;mysql:host=localhost;dbname=school&#39;,&#39;root&#39;,&#39;root&#39;);
    //查询一条记录
    //$sql=&#39;select * from t_teacher where id=5&#39;;
    //查询多条记录
    $sql=&#39;select * from t_teacher&#39;;
    //$pdo->query($sql):执行sql语句,返回PDOStatement对象:需要遍历这个对象,将里面的内容取出来
    $stmt=$pdo->query($sql);
    var_dump($stmt); //只能看出这个语句返回的是一个对象
    echo &#39;<hr/>&#39;;
    foreach ($stmt as $row){
        print_r($row);
        echo &#39;<hr/>&#39;;
        echo &#39;编号:&#39;.$row[&#39;id&#39;].&#39;<br/>&#39;;
        echo &#39;用户名:&#39;.$row[&#39;teaname&#39;].&#39;<br/>&#39;;
        echo &#39;邮箱:&#39;.$row[&#39;email&#39;].&#39;<br/>&#39;;
        echo &#39;<hr/>&#39;;
    }
}catch (PDOException $e){
    echo $e->getMessage();
};
Copy after login
Query()用于插入数据

<?php
try{
    //驱动器的名称 mysql
    $pdo=new PDO(&#39;mysql:host=localhost;dbname=school&#39;,&#39;root&#39;,&#39;root&#39;);
    //插入一条记录
    $sql=&#39;insert into t_teacher values(default,"king12","&#39;.md5(&#39;king&#39;).&#39;","waly@qq.com");&#39;;
    //$pdo->query($sql):执行sql语句,返回PDOStatement对象:需要遍历这个对象,将里面的内容取出来
    $stmt=$pdo->query($sql);
    var_dump($stmt); //只能看出这个语句返回的是一个对象
}catch (PDOException $e){
    echo $e->getMessage();
};
Copy after login

注意:更多的用query()查询数据,用exec()实现增删改

2-6 [PDO] prepare()和execute()方法执行查询语句

Detailed tutorials and practical demonstrations on connecting to the database with PDO in PHP

<?php

//查询单条语句

try{
    //驱动器的名称 mysql
    $pdo=new PDO(&#39;mysql:host=localhost;dbname=school&#39;,&#39;root&#39;,&#39;root&#39;);
    //查询一条记录
   $sql=&#39;select * from t_teacher where id=5&#39;;
   //$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();
};
Copy after login
<?php
try{
    //驱动器的名称 mysql
    $pdo=new PDO(&#39;mysql:host=localhost;dbname=school&#39;,&#39;root&#39;,&#39;root&#39;);
    //查询多条记录
    $sql=&#39;select * from t_teacher&#39;;
    //$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 &#39;<hr/>&#39;;
        }
    }*/
    //fetchAll() 查询所有记录,以二维数组(索引+关联方式)
 $rows=$stmt->fetchAll();
print_r($rows);
}catch (PDOException $e){
    echo $e->getMessage();
};
Copy after login

指定类型:我们更多的是想得到关联数组,我们可以通过两种方式来获得,第一种方式:设置其取回数据的方式(设置参数、常量);第二种方式:通过方法

三、 PDOStatement对象的使用

本章主要介绍PDOStatement对象方法的使用,以及参数的绑定与预处识。

Detailed tutorials and practical demonstrations on connecting to the database with PDO in PHP

3-1 [PDO] quote()方法防止SQL注入

带条件查询 登录实现的例子

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);
$username=$_POST[&#39;username&#39;];
$password=$_POST[&#39;password&#39;];
try{
    //连接数据库
    $pdo=new PDO(&#39;mysql:host=localhost;dbname=school&#39;,&#39;root&#39;,&#39;root&#39;);
    //向数据库表查找对应的用户信息//如果存在,证明有这个用户,登录成功;否则登录失败
    //输入 &#39;or 1=1 # 可以查看查到的数据
    //$sql="select * from t_user WHERE `name`=&#39;{$username}&#39; AND  `password`=&#39;{$password}&#39;";    //通过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();
}
Copy after login

3-2 [PDO] 预处理语句中的占位符的使用

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);
$username=$_POST[&#39;username&#39;];
$password=$_POST[&#39;password&#39;];
try{
    //连接数据库
    $pdo=new PDO(&#39;mysql:host=localhost;dbname=school&#39;,&#39;root&#39;,&#39;root&#39;);
    //占位符有两种方法
    //第一种方法
    $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();
}
Copy after login

3-3 [PDO] bindParam()方法绑定参数

两种方式:命名参数占位符,问号方式

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);
try{
    //连接数据库
    $pdo=new PDO(&#39;mysql:host=localhost;dbname=school&#39;,&#39;root&#39;,&#39;root&#39;);
   // $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=&#39;张三&#39;;
    $password=&#39;123654&#39;;
    $sex=&#39;M&#39;;
   $stmt->execute();
   echo $stmt->rowCount();
}catch (PDOException $e){
    echo $e->getMessage();
}
Copy after login
<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);
try{
    //连接数据库
    $pdo=new PDO(&#39;mysql:host=localhost;dbname=school&#39;,&#39;root&#39;,&#39;root&#39;);
    // $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=&#39;张三1&#39;;
    $password=&#39;1236541&#39;;
    $sex=&#39;F&#39;;
    $stmt->execute();
    echo $stmt->rowCount();
}catch (PDOException $e){
    echo $e->getMessage();
}
Copy after login

3-4 [PDO] bindValue()方法绑定参数

向用户表插入数据:命名参数占位符,问号方式类似

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);
try{
    //连接数据库
    $pdo=new PDO(&#39;mysql:host=localhost;dbname=school&#39;,&#39;root&#39;,&#39;root&#39;);
    // $sql="insert into t_user(`name`,`password`,`sex`) VALUES (:username,:password,:sex)";
    $sql="insert into t_user VALUES (DEFAULT ,?,?,?)";
    $stmt=$pdo->prepare($sql);
    $username=&#39;李四&#39;;
    $password=&#39;123654&#39;;
    $stmt->bindValue(1,$username);
    $stmt->bindValue(2,$password);
    $stmt->bindValue(3,&#39;M&#39;);
    $stmt->execute();
    echo $stmt->rowCount();
    $username=&#39;李四1&#39;;
    $password=&#39;1236541&#39;;
    $stmt->bindValue(1,$username);
    $stmt->bindValue(2,$password);
    $stmt->bindValue(3,&#39;M&#39;);
    $stmt->execute();
    echo $stmt->rowCount();
}catch (PDOException $e){
    echo $e->getMessage();
}
Copy after login

3-5 [PDO] bindColumn()方法绑定参数

Detailed tutorials and practical demonstrations on connecting to the database with PDO in PHP

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);
try{
    //连接数据库
    $pdo=new PDO(&#39;mysql:host=localhost;dbname=school&#39;,&#39;root&#39;,&#39;root&#39;);
    // $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 &#39;结果集中的列数一共有:&#39;.$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 &#39;用户名:&#39;.$username."-密码:".$password."-性别:".$sex."<hr/>";
    }
    echo $stmt->rowCount();
}catch (PDOException $e){
    echo $e->getMessage();
}
Copy after login

3-6 [PDO] fetchColumn()方法从结果集中返回一列

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);
try{
    //连接数据库
    $pdo=new PDO(&#39;mysql:host=localhost;dbname=school&#39;,&#39;root&#39;,&#39;root&#39;);    $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();
}
Copy after login

3-7 [PDO] debugDumpParams()方法打印一条预处理语句

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);
try{
    //连接数据库
    $pdo=new PDO(&#39;mysql:host=localhost;dbname=school&#39;,&#39;root&#39;,&#39;root&#39;);
    // $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=&#39;张三&#39;;
    $password=&#39;123654&#39;;
    $sex=&#39;M&#39;;
    $stmt->execute();
    $stmt->debugDumpParams();
}catch (PDOException $e){
    echo $e->getMessage();
}
Copy after login

四、PDO事务处理

主要介绍如何使用PDO进行事务处理

4-1 PDO错误处理模式

3种错误处理模式

静默模式

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);
 /*PDO::ERRMODE_SLIENT:默认模式,静默模式*/
try{
    //连接数据库
    $pdo=new PDO(&#39;mysql:host=localhost;dbname=school&#39;,&#39;root&#39;,&#39;root&#39;);
    $sql="select * from nonet_user";
    $stmt=$pdo->query($sql);
    echo $pdo->errorCode();
    echo &#39;<br/>&#39;;
    echo $pdo->errorInfo();
}catch (PDOException $e){
    echo $e->getMessage();
}
Copy after login
<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);
 /*PDO::ERRMODE_SLIENT:默认模式,静默模式
 *PDO::ERRMODE_WARNING:警告模式
  * PDO::ERRMODE_EXCEPTION:异常模式
 */
try{
    //连接数据库
    $pdo=new PDO(&#39;mysql:host=localhost;dbname=school&#39;,&#39;root&#39;,&#39;root&#39;);
   //设置警告模式
    //$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 &#39;<br/>&#39;;
    echo $pdo->errorInfo();
}catch (PDOException $e){
    echo $e->getMessage();
}
Copy after login

4-2 PDO事务处理

Detailed tutorials and practical demonstrations on connecting to the database with PDO in PHP

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);
try{
    $option=array(PDO::ATTR_AUTOCOMMIT,0);
    $pdo=new PDO(&#39;mysql:host=localhost;dbname=school&#39;,&#39;root&#39;,&#39;root&#39;,$option);
//开启事务
    $pdo->beginTransaction();
    var_dump($pdo->inTransaction());
    $sql="update account set money=money-200  WHERE username=&#39;king&#39;";
    $res=$pdo->exec($sql);
    if($res==0){
        throw new PDOException(&#39;转账失败&#39;);
    }
    $res1=$pdo->exec(&#39;update account set money=money+200  WHERE username="queen"&#39;);
    if($res1==0){
        throw new PDOException(&#39;接收失败&#39;);
    }
    $pdo->commit();
}catch (PDOException $e){
    $pdo->rollBack();
    echo $e->getMessage();
}
Copy after login

好了,以上就是关于本文介绍的关于PHP中PDO操作数据库的详细操作以及实例了,相了解更多相关问题请访问PHP中文网:

PHP视频教程

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!

Related labels:
pdo
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template