Home Backend Development PHP Tutorial How to use PDO to query Mysql in Php to avoid the risk of SQL injection_PHP Tutorial

How to use PDO to query Mysql in Php to avoid the risk of SQL injection_PHP Tutorial

Jul 21, 2016 pm 03:11 PM
c mysql pdo php sql use us method Inquire injection of avoid risk

When we use 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, causing the website to be attacked and out of control. 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 process various databases, 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: 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" to connect Database, you also need to remove the ";" sign in front of the database extension related to PDO (usually php_pdo_mysql.dll is used), and then restart the Apache server.

Copy code The code is as follows:

extension=php_pdo.dll
extension=php_pdo_mysql.dll

2. PDO connects to mysql database
Copy code The code is as follows:

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

The default is not a persistent connection. If you want to use a database persistent connection, you need to add it at the end The following parameters:
Copy code The code is as follows:

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

3. PDO setting properties

1) 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 exceptions

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

Copy the code The code is as follows:

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

When set to PDO::ERrmODE_SILENT, you can get the error information by calling errorCode() or errorInfo(), of course others It's also possible.

2) Because different databases handle the case of returned field names differently, PDO provides the PDO::ATTR_CASE setting item (including PDO::CASE_LOWER, PDO::CASE_NATURAL, PDO::CASE_UPPER) to determine the returned The case of field names.

3) 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 operations that return recorded results, especially SELECT operations
PDO::exec() Mainly for operations that do not return a result set, such as INSERT, UPDATE and other operations
PDO::prepare() is mainly a preprocessing operation, and you need to use $rs->execute() to execute the SQL statement in the preprocessing. This method can bind parameters and is quite powerful (preventing SQL injection depends on this)
PDO::lastInsertId() returns the last insertion operation. The primary key column type is the last auto-incremented ID
PDOStatement: :fetch() is used to get a record
PDOStatement::fetchAll() is used to get all records into a collection
PDOStatement::fetchColumn() is used to get a certain field of the first record specified in the result. If it is missing The province is the first field
PDOStatement::rowCount(): mainly used for the result set affected by PDO::query() and PDO::prepare()'s DELETE, INSERT, and UPDATE operations, and for PDO::exec () method and SELECT operation are invalid.

5. PDO operation MYSQL database instance

Copy code The code is as follows:

< ?php
$pdo = new PDO("mysql:host=localhost;dbname=db_demo","root","");
if($pdo -> exec("insert into db_demo(name, content) values('title','content')")){
echo "Insertion successful! ";
echo $pdo -> lastinsertid();
}
?>

Copy code The code is as follows:

$pdo = new PDO("mysql:host=localhost;dbname=db_demo","root","");
$rs = $pdo -> query("select * from test");
$rs->setFetchMode(PDO::FETCH_ASSOC); //Associative array form
//$rs->setFetchMode(PDO::FETCH_NUM); / /numeric index array form
while($row = $rs -> fetch()){
print_r($row);
}
?>

Copy code The code is as follows:

foreach( $db->query( "SELECT * FROM feeds" ) as $row )
{
print_r( $row );
}
?>

Count how many rows of data there are
Copy code The code is as follows:

$sql="select count(*) from test";
$num = $dbh-> query($sql)->fetchColumn();

prepare method
Copy code The code is as follows:

$stmt = $dbh->prepare("select * from test");
if ($stmt->execute()) {
while ($row = $stmt-> ;fetch()) {
print_r($row);
}
}

Prepare parameterized query
Copy code The code is as follows:

$stmt = $dbh->prepare("select * from test where name = ?");
if ($stmt-> execute(array("david"))) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
print_r($row);
}
}

[Let’s talk about the key points, how to prevent sql injection]

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:

Copy the code The code is as follows:

$dbh = new PDO('mysql: dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass');
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
setAttribute() line is mandatory and tells PDO to disable emulation of prepared statements and use real parepared statements. This ensures that the SQL statement and corresponding values ​​are not parsed by PHP before being passed to the mysql server (disabling all possible malicious SQL injection attacks). Although you can set the character set attribute (charset=utf8) in the configuration file, it is important to note that older versions of PHP (< 5.3.6) ignore character parameters in DSN.

Let’s look at a complete code usage example:


Copy the code The code is as follows:
$dbh = new PDO ("mysql:host=localhost; dbname=demo", "user", "pass");
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //Disable the simulation effect of prepared statements
$dbh->exec("set names 'utf8'");
$sql="select * from test where name = ? and password = ?";
$stmt = $dbh->prepare ($sql);
$exeres = $stmt->execute(array($testname, $pass));
if ($exeres) {
while ($row = $stmt-> fetch(PDO::FETCH_ASSOC)) {
print_r($row);
}
}
$dbh = null;

The above code can prevent this sql injection. Why?
When prepare() is called, the query statement has been sent to the database server. At this time, only the placeholder? is sent, and there is no user-submitted data; when execute() is called, the value submitted by the user will be Sent to the database, they are sent separately. The two are independent, and SQL attackers have no chance.

But we need to pay attention to the following situations. PDO cannot help you prevent SQL injection

1. You cannot let the placeholder ? replace a set of values, such as:


Copy the code The code is as follows:
SELECT * FROM blog WHERE userid IN (?);

2. You cannot let placeholders replace the data table name or column name, such as:

Copy code The code is as follows:
SELECT * FROM blog ORDER BY ?;

3. You cannot let the placeholder ? replace any other SQL syntax, such as:

Copy code The code is as follows:

SELECT EXTRACT( ? FROM datetime_column) AS variable_datetime_element FROM blog;

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/326795.htmlTechArticleWhen we use the traditional mysql_connect and mysql_query methods to connect and query the database, if the filtering is not strict, there will be SQL injection The risk may lead to the website being attacked and losing control. Although...
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1668
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
MySQL: The Database, phpMyAdmin: The Management Interface MySQL: The Database, phpMyAdmin: The Management Interface Apr 29, 2025 am 12:44 AM

MySQL and phpMyAdmin can be effectively managed through the following steps: 1. Create and delete database: Just click in phpMyAdmin to complete. 2. Manage tables: You can create tables, modify structures, and add indexes. 3. Data operation: Supports inserting, updating, deleting data and executing SQL queries. 4. Import and export data: Supports SQL, CSV, XML and other formats. 5. Optimization and monitoring: Use the OPTIMIZETABLE command to optimize tables and use query analyzers and monitoring tools to solve performance problems.

Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

Steps to add and delete fields to MySQL tables Steps to add and delete fields to MySQL tables Apr 29, 2025 pm 04:15 PM

In MySQL, add fields using ALTERTABLEtable_nameADDCOLUMNnew_columnVARCHAR(255)AFTERexisting_column, delete fields using ALTERTABLEtable_nameDROPCOLUMNcolumn_to_drop. When adding fields, you need to specify a location to optimize query performance and data structure; before deleting fields, you need to confirm that the operation is irreversible; modifying table structure using online DDL, backup data, test environment, and low-load time periods is performance optimization and best practice.

What is the significance of the session_start() function? What is the significance of the session_start() function? May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

How to uninstall MySQL and clean residual files How to uninstall MySQL and clean residual files Apr 29, 2025 pm 04:03 PM

To safely and thoroughly uninstall MySQL and clean all residual files, follow the following steps: 1. Stop MySQL service; 2. Uninstall MySQL packages; 3. Clean configuration files and data directories; 4. Verify that the uninstallation is thorough.

An efficient way to batch insert data in MySQL An efficient way to batch insert data in MySQL Apr 29, 2025 pm 04:18 PM

Efficient methods for batch inserting data in MySQL include: 1. Using INSERTINTO...VALUES syntax, 2. Using LOADDATAINFILE command, 3. Using transaction processing, 4. Adjust batch size, 5. Disable indexing, 6. Using INSERTIGNORE or INSERT...ONDUPLICATEKEYUPDATE, these methods can significantly improve database operation efficiency.

How to use MySQL functions for data processing and calculation How to use MySQL functions for data processing and calculation Apr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

Composer: The Package Manager for PHP Developers Composer: The Package Manager for PHP Developers May 02, 2025 am 12:23 AM

Composer is a dependency management tool for PHP, and manages project dependencies through composer.json file. 1) parse composer.json to obtain dependency information; 2) parse dependencies to form a dependency tree; 3) download and install dependencies from Packagist to the vendor directory; 4) generate composer.lock file to lock the dependency version to ensure team consistency and project maintainability.

See all articles