Home  >  Article  >  Backend Development  >  How to prevent sql injection in php

How to prevent sql injection in php

(*-*)浩
(*-*)浩Original
2019-09-19 11:06:374929browse

Need to prevent sql injection when querying the database

How to prevent sql injection in php

Implementation method:

PHP comes with its own method SQL statements can be escaped, and backslashes are added before certain characters when required in database query statements. These characters are single quotes ('), double quotes ("), backslash (\) and NUL (NULL character). (Recommended learning: PHP Programming from Beginner to Master)

string addslashes ( string $str )//该函数返回一个字符串

Example

<?php
$str = "Is your name O&#39;reilly?";

// 输出: Is your name O\&#39;reilly?
echo addslashes($str);
?>

ThinkPHP automatically provides security protection. For string type data, ThinkPHP will perform escape_string processing (real_escape_string, mysql_escape_string)

To effectively prevent SQL injection Question, official recommendation:

Try to use arrays for query conditions, which is a safer way;

If you must use string query conditions as a last resort, use the preprocessing mechanism;

Use automatic verification and automatic completion mechanisms for custom filtering of applications;

If the environment permits, try to use PDO and use parameter binding.

Query condition preprocessing

This method is similar to putting a placeholder in the query statement, and then passing in the parameters in the form of an array

For example:

$Model->where("id=%d and username=&#39;%s&#39; and xx=&#39;%f&#39;",array($id,$username,$xx))->select();

$Model->where("id=%d and username=&#39;%s&#39; and xx=&#39;%f&#39;",$id,$username,$xx)->select();

The above is the detailed content of How to prevent sql injection in php. 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