Hongmu Notes
Home Language Notes Prevent SQL injection when php queries the database
Language Notes PHP

Prevent SQL injection when php queries the database

Prevent SQL injection when php queries the database

There are two primary methods for preventing SQL injection in PHP:

  1. Use of preprocessed statements

Prepared statements involve preparing a query statement in advance and then passing parameters into it; this approach helps prevent SQL injection attacks. In PHP, you can implement prepared statements using the PDO or mysqli extensions. Below is an example of how to use prepared statements with the mysqli extension:

// 数据库连接
$host = 'localhost';
$user = 'username';
$pass = 'password';
$dbName = 'database_name';
$db = mysqli_connect($host, $user, $pass, $dbName);
if (!$db) {
  die("无法连接到数据库: " . mysqli_connect_error());
}

// 防止SQL注入
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  $username = $_POST['username'];
  $password = $_POST['password'];
  
  $stmt = $db->prepare("SELECT * FROM users WHERE username=? AND password=?");
  $stmt->bind_param("ss", $username, $password);
  $stmt->execute();
  $result = $stmt->get_result();

  // 处理查询结果
}

In the above code, we have used MySQLi.prepare()A function is used to construct the query statement, where parameter placeholders (?) are employed to replace the actual parameters. Then, it is used.bind_param()A function is used to bind parameters; here, the first parameter "ss" indicates that all subsequent parameters are of string type. This ensures correct parameter passing and mitigates the risk of SQL injection.

  1. Escape special characters

In addition to using prepared statements, we can also escape special characters, for example by usingmysqli_real_escape_stringThe `escape` function escapes special characters into safe characters. The following is an example of using this function to escape special characters:

// 数据库连接
$host = 'localhost';
$user = 'username';
$pass = 'password';
$dbName = 'database_name';
$db = mysqli_connect($host, $user, $pass, $dbName);
if (!$db) { 
  die("无法连接到数据库: " . mysqli_connect_error()); 
}

// 防止SQL注入
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  $username = mysqli_real_escape_string($db, $_POST['username']);
  $password = mysqli_real_escape_string($db, $_POST['password']);
  
  $sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
  $result = mysqli_query($db, $sql);

  // 处理查询结果
}

In the above code, we have usedmysqli_real_escape_stringThe function escapes the data, ensuring that the input does not contain special characters, thereby preventing SQL injection attacks.

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP ob function record

PHP ob function record Language Notes PHP

Usage of the following three functions ob_get_contents(); ob_end_clean(); ob_start(); You can use these functions to buffer local files and execute local script code. Use ob_start() to save the output code into the buffer, and the page will not be displayed; then use ob_get_contents to get the data in the buffer. o…
👁 141
PHP preg

PHP preg Language Notes PHP

The preg_match_all function is used to perform a global regular expression match. preg_match_all() Syntax int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG…
👁 169
Detailed explanation of PHP ternary operator and if

Detailed explanation of PHP ternary operator and if Language Notes PHP

Ternary operator condition ? Result 1 : Result 2 Explanation: The position in front of the question mark is the condition for judgment. If the condition is met, the result is 1, and if it is not met, the result is 2. This article compares and explains the ternary operator and if...else... in detail. I hope it will be helpful to everyone. Today when I was revising my paper online, I encountered a statement that I couldn’t understand: $if_summary = $row['IF_SUMMARY']=…
👁 189
PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232

Recommended reading

Acupuncture and moxibustion acupoint markings on the human body

Acupuncture and moxibustion acupoint markings on the human body Hobbies Memo notes

Ren meridian Ren meridian acupoint song Ren meridian thirty-eight starts from the perineum, the pole in the curved bone is Guan Yuanrui, Shimen qi and sea yin still intersect, and the water from Shenque flows down to the epigastrium. The middle and upper buildings of the building are connected, with a huge dove tail covering the bones, a Mu Yu Hall in the middle of the atrium, and a purple palace canopy at night. Tiantu's throat is Lianquan, and there are twenty-four points under the lip. This sutra does not take the combination of Jing Ying and Shu. The pulse starts below the middle pole, above the hairline, along the Guanyuan in the abdomen, to the throat. It belongs to the sea of ​​yin veins. It flows around the divisions of yin as human veins, just like water...
👁 672
(Adaptive mobile phone version) Sheet metal processing equipment website pbootcms template Machinery manufacturing inspection website source code download 0412

(Adaptive mobile phone version) Sheet metal processing equipment website pbootcms template Machinery manufacturing inspection website source code download 0412 Practical Collection pbootcms Template

A mobile-adaptive PbootCMS website template for sheet metal processing equipment and machinery manufacturing inspection. The design style is professional and sophisticated, suitable for displaying sheet metal equipment, testing instruments and processing services. It helps machinery manufacturing companies showcase their technologies online and attract precision manufacturing customers. Template display Installation instructions Website backend:/admin.php Account: admin Password: admin Unzip password: www.4s5.cn Related...
👁 47
(Adaptive mobile version) Environmental protection equipment website template Filter equipment website source code download 1147

(Adaptive mobile version) Environmental protection equipment website template Filter equipment website source code download 1147 Practical Collection pbootcms Template

A PbootCMS website template for environmental protection equipment and filtering equipment, supporting PC and WAP. The design style is professional and technological, suitable for displaying environmentally friendly filtration equipment products and technical solutions. It helps environmental protection equipment companies display their products online and attract industrial and municipal customers. Template display Installation instructions Website backend:/admin.php Account: admin Password: admin Unzip password: www.4s5.cn Related articles…
👁 61
Marketing-oriented plastic sheet purification and environmental protection equipment website template – 0734

Marketing-oriented plastic sheet purification and environmental protection equipment website template – 0734 Practical Collection Yiyou template

An EyouCMS website template designed for enterprises specializing in marketing-oriented plastic sheet products and environmental purification equipment. Its eco-friendly design is ideal for showcasing plastic sheet products, purification equipment, and technical solutions. This template helps environmental materials companies showcase their products online and attract industrial customers. Template Demo | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | Eyou...
👁 47
Imperial cms imitation website tutorial corresponding notes

Imperial cms imitation website tutorial corresponding notes Program Notes Empire cms

Hello everyone, welcome to learn the imperial cms imitation website tutorial. I am Hong Mu qq1810216796 QQ exchange group: 9589723231 Imperial cms website installation. Hello everyone, welcome to learn the imperial cms imitation website tutorial. I am Hong Mu qq: 1810216796 qq exchange group: 958972323 Build an imperial program. If you have a server and have built an imperial website on the server, then...
👁 3413
How to implement PJAX on a website

How to implement PJAX on a website Language Notes PHP

PJAX (PushState + AJAX) is a page-load technique that enables seamless page navigation and partial content updates on websites without refreshing the entire page. Below is a brief guide on how to use PJAX to implement non-refreshing page loading on a website: Integrate the PJAX library – First, include the PJAX library on your website, such as pjax.js or the jQuery pjax plugin...
👁 197