search
HomeDatabaseMysql TutorialHow to use PDO to query mysql to avoid SQL injection
How to use PDO to query mysql to avoid SQL injectionJun 09, 2018 pm 02:03 PM
pdosql injection

When using the traditional mysql_connect and mysql_query methods to connect and query the database, if the filtering is not strict, there is a risk of SQL injection. Although the mysql_real_escape_string() function can be used to filter user-submitted values, it also has flaws. By using the prepare method of PHP's PDO extension, you can avoid the risk of sql injection.

PDO (PHP Data Object) is a major new feature added to PHP5, because before PHP 5, php4/php3 had a bunch of database extensions to connect and connect with each database. Processing, such as php_mysql.dll. PHP6 will also use PDO to connect by default, and the mysql extension will be used as an auxiliary. Official address: http://php.net/manual/en/book.pdo.php

1. PDO configuration

Before using the PDO extension, you must first enable this extension. In php.ini, remove the ";" in front of "extension=php_pdo.dll". If you want to connect to the database, you also need to remove the PDO-related database extension. ";" (usually php_pdo_mysql.dll is used), and then restart the Apache server.

extension=php_pdo.dll 
extension=php_pdo_mysql.dll

2. PDO connects to mysql database

$dbh = new PDO("mysql:host=localhost;dbname=mydb","root","password");

The default is not a long connection. If you want to use a long connection to the database, you can add it at the end Add the following parameters:

$dbh = new PDO("mysql:host=localhost;dbname=mydb","root","password","array(PDO::ATTR_PERSISTENT => true) "); 
$dbh = null; //(释放)

3. PDO setting properties

PDO has three error handling methods:

PDO::ERrmODE_SILENT does not display error messages, only sets error codes

PDO::ERrmODE_WARNING displays warning errors

PDO::ERrmODE_EXCEPTION throws an exception

You can use the following statement to set the error handling method to throw an exception

$db->setAttribute(PDO::ATTR_ERrmODE, PDO::ERrmODE_EXCEPTION);

Because different database pairs return The case of field names is handled differently, so PDO provides the PDO::ATTR_CASE setting item (including PDO::CASE_LOWER, PDO::CASE_NATURAL, PDO::CASE_UPPER) to determine the case of the returned field name.

Specify the corresponding value in php for the NULL value returned by the database by setting the PDO::ATTR_ORACLE_NULLS type (including PDO::NULL_NATURAL, PDO::NULL_EmpTY_STRING, PDO::NULL_TO_STRING).

4. Common PDO methods and their applications

PDO::query() is mainly used for records Operations that return results, especially SELECT operations

PDO::exec() is mainly for operations that do not return a result set, such as INSERT, UPDATE and other operations

PDO::prepare() is mainly a preprocessing operation. You need to use $rs->execute() to execute the SQL statement in the preprocessing. This method can bind parameters and is more powerful (preventing sql injection Just rely on this)

PDO::lastInsertId() returns the last insert operation, the primary key column type is the last auto-increment ID

PDOStatement::fetch() is used to obtain a record

PDOStatement::fetchAll() is used to obtain all record sets into a collection

PDOStatement::fetchColumn() is a field of the first record specified in the fetch result. The default is the first field.

PDOStatement::rowCount(): Mainly used The result set affected by DELETE, INSERT, and UPDATE operations on PDO::query() and PDO::prepare() is invalid for the PDO::exec() method and SELECT operation.


5.PDO operation MYSQL database instance

<?php 
$pdo = new PDO("mysql:host=localhost;dbname=mydb","root",""); 
if($pdo -> exec("insert into mytable(name,content) values(&#39;fdipzone&#39;,&#39;123456&#39;)")){ 
echo "insert success"; 
echo $pdo -> lastinsertid(); 
} 
?>
<?php 
$pdo = new PDO("mysql:host=localhost;dbname=mydb","root",""); 
$rs = $pdo -> query("select * from table"); 
$rs->setFetchMode(PDO::FETCH_ASSOC); //关联数组形式
//$rs->setFetchMode(PDO::FETCH_NUM); //数字索引数组形式
while($row = $rs -> fetch()){ 
    print_r($row); 
} 
?>
<?php
foreach( $db->query( "SELECT * FROM table" ) as $row )
{
    print_r( $row );
}
?>

Statistics on how many rows of data there are:

<?php
$sql="select count(*) from table";
$num = $dbh->query($sql)->fetchColumn();
?>

prepare method:

<?php $query = $dbh->prepare("select * from table");
if ($query->execute()) {
    while ($row = $query->fetch()) {
        print_r($row);
    }
}
?>

prepare parameterized query:

<?php
$query = $dbh->prepare("select * from table where id = ?");
if ($query->execute(array(1000))) { 
    while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
        print_r($row);
    }
}
?>

When using PDO to access the MySQL database , real prepared statements are not used by default. To solve this problem, you must disable the emulation effects of prepared statements. The following is an example of using PDO to create a link:

<?php
$dbh = new PDO(&#39;mysql:dbname=mydb;host=127.0.0.1;charset=utf8&#39;, &#39;root&#39;, &#39;pass&#39;);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
?>

setAttribute()这一行是强制性的,它会告诉 PDO 禁用模拟预处理语句,并使用 real parepared statements 。这可以确保SQL语句和相应的值在传递到mysql服务器之前是不会被PHP解析的(禁止了所有可能的恶意SQL注入攻击)。

虽然你可以配置文件中设置字符集的属性(charset=utf8),但是需要格外注意的是,老版本的 PHP(

完整的代码使用实例:

<?php
$dbh = new PDO("mysql:host=localhost; dbname=mydb", "root", "pass");
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //禁用prepared statements的仿真效果
$dbh->exec("set names &#39;utf8&#39;"); 
$sql="select * from table where username = ? and password = ?";
$query = $dbh->prepare($sql); 
$exeres = $query->execute(array($username, $pass)); 
if ($exeres) { 
    while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
        print_r($row);
    }
}
$dbh = null;
?>

上面这段代码就可以防范sql注入。为什么呢?

当调用 prepare() 时,查询语句已经发送给了数据库服务器,此时只有占位符 ? 发送过去,没有用户提交的数据;当调用到 execute()时,用户提交过来的值才会传送给数据库,它们是分开传送的,两者独立的,SQL攻击者没有一点机会。

但是我们需要注意的是以下几种情况,PDO并不能帮助你防范SQL注入。

不能让占位符 ? 代替一组值,这样只会获取到这组数据的第一个值,如:

select * from table where userid in ( ? );

如果要用in來查找,可以改用find_in_set()实现

$ids = &#39;1,2,3,4,5,6&#39;;
select * from table where find_in_set(userid, ?);

不能让占位符代替数据表名或列名,如:

select * from table order by ?;

不能让占位符 ? 代替任何其他SQL语法,如:

select extract( ? from addtime) as mytime from table;

本篇文章如何使用PDO查询mysql避免SQL注入的方法,更多相关内容请关注php中文网。

相关推荐:

关于php 双向队列类的讲解

php heredoc 与 nowdoc之间的区别与特点

关于HTML5 localStorage and sessionStorage 之间的区别

The above is the detailed content of How to use PDO to query mysql to avoid SQL injection. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
PHP Fatal error: Call to undefined method PDO::prepare() in的解决方法PHP Fatal error: Call to undefined method PDO::prepare() in的解决方法Jun 22, 2023 pm 06:40 PM

PHP作为一种流行的Web开发语言,已经被使用了很长时间。PHP中集成的PDO(PHP数据对象)类是我们在开发Web应用程序过程中与数据库进行交互的一种常用方法。但是,一些PHP开发者经常遇到的问题是,当使用PDO类与数据库进行交互时,他们会收到这样的错误:PHPFatalerror:CalltoundefinedmethodPDO::prep

php如何使用PHP的PDO_PGSQL扩展?php如何使用PHP的PDO_PGSQL扩展?Jun 02, 2023 pm 06:10 PM

PHP作为一种流行的编程语言,在Web开发领域中有着广泛的应用。其中,PHP的PDO_PGSQL扩展是一种常用的PHP扩展,它提供了与PostgreSQL数据库的交互接口,可以实现PHP与PostgreSQL之间的数据传输和交互。本文将详细介绍如何使用PHP的PDO_PGSQL扩展。一、什么是PDO_PGSQL扩展?PDO_PGSQL是PHP的一个扩展库,它

PHP和PDO: 如何执行批量插入和更新PHP和PDO: 如何执行批量插入和更新Jul 28, 2023 pm 07:41 PM

PHP和PDO:如何执行批量插入和更新导言:在使用PHP编写数据库相关的应用程序时,经常会遇到需要批量插入和更新数据的情况。传统的做法是使用循环来执行多次数据库操作,但这样的方法效率较低。PHP的PDO(PHPDataObject)提供了一种更高效的方法来执行批量插入和更新操作,本文将介绍如何使用PDO来实现批量插入和更新。一、PDO简介:PDO是PH

PHP和PDO: 如何处理数据库中的JSON数据PHP和PDO: 如何处理数据库中的JSON数据Jul 29, 2023 pm 05:17 PM

PHP和PDO:如何处理数据库中的JSON数据在现代web开发中,处理和存储大量数据是一个非常重要的任务。随着移动应用和云计算的普及,越来越多的数据以JSON(JavaScriptObjectNotation)格式存储在数据库中。PHP作为一种常用的服务器端语言,它的PDO(PHPDataObject)扩展提供了一种方便的方式来处理和操作数据库。本

PHP和PDO: 如何进行分页查询和显示数据PHP和PDO: 如何进行分页查询和显示数据Jul 29, 2023 pm 04:10 PM

PHP和PDO:如何进行分页查询和显示数据在开发Web应用程序时,分页查询和显示数据是一个非常常见的需求。通过分页,我们可以一次显示一定数量的数据,提高页面加载速度和用户体验。在PHP中,使用PHP数据对象(PDO)库可以轻松实现分页查询和显示数据的功能。本文将介绍如何在PHP中使用PDO进行分页查询和显示数据,并提供相应的代码示例。一、创建数据库和数据表

如何使用PDO连接到Redis数据库如何使用PDO连接到Redis数据库Jul 28, 2023 pm 04:29 PM

如何使用PDO连接到Redis数据库Redis是一个开源的高性能、内存存储的键值数据库,常用于缓存、队列等场景。在PHP开发中,使用Redis可以有效提升应用的性能和稳定性。而通过PDO(PHPDataObjects)扩展,我们可以更方便地连接和操作Redis数据库。本文将介绍如何使用PDO连接到Redis数据库,并附带代码示例。安装Redis扩展在开始

PHP和PDO: 如何执行数据库备份和还原操作PHP和PDO: 如何执行数据库备份和还原操作Jul 29, 2023 pm 06:54 PM

PHP和PDO:如何执行数据库备份和还原操作在开发Web应用程序时,数据库的备份和还原是非常重要的任务。PHP作为一门流行的服务器端脚本语言,提供了丰富的库和扩展,其中PDO(PHP数据对象)是一款强大的数据库访问抽象层。本文将介绍如何使用PHP和PDO来执行数据库备份和还原操作。第一步:连接数据库在实际操作之前,我们需要建立与数据库的连接。使用PDO对

如何使用PDO绑定和获取绑定参数值如何使用PDO绑定和获取绑定参数值Jul 28, 2023 pm 07:09 PM

如何使用PDO绑定和获取绑定参数值在开发Web应用程序时,处理数据库查询是很常见的任务之一。为了保证应用程序的安全性和可靠性,我们应该使用参数绑定来处理SQL查询,而不是直接将变量值插入SQL语句中。PDO(PHP数据对象)提供了一种方便且安全的方式来绑定参数和获取绑定参数的值。下面,我们将介绍如何使用PDO进行参数绑定和获取绑定参数的

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.