Hongmu Notes
Home Language Notes When querying a database using PHP, can `Mysqli::real_escape_string` be replaced with another function?
Language Notes PHP

When querying a database using PHP, can `Mysqli::real_escape_string` be replaced with another function?

When querying a database using PHP, can `Mysqli::real_escape_string` be replaced with another function?

mysqli_real_escape_stringThis is a built-in PHP function and one of the commonly used methods to prevent SQL injection attacks. When replacing it with another function, the new function must support the escaping of special characters; for example, you can use the `PDO` method.PDO::quoteFunction SumbindParamThis method achieves the same effect. Additionally, other approaches can be used.addslashesEscape the function.

Here is an example code using PDO and the addslashes function:

Example code using PDO:

// 数据库连接
$host = 'localhost';
$user = 'username';
$pass = 'password';
$dbName = 'database_name';
$dsn = "mysql:host=$host;dbname=$dbName;charset=utf8mb4";
$options = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
];
$pdo = new PDO($dsn, $user, $pass, $options);

// 防止SQL注入
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  $username = $_POST['username'];
  $password = $_POST['password'];
  
  $username = $pdo->quote($username);
  $password = $pdo->quote($password);

  $sql = "SELECT * FROM users WHERE username=$username AND password=$password";
  $stmt = $pdo->query($sql);
  $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

  // 处理查询结果
}

In the above code, we usePDO::quoteThis function escapes special characters in the input string, making it safe to use when constructing SQL statements.

UseaddslashesExample code:

// 数据库连接
$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 = addslashes($_POST['username']);
  $password = addslashes($_POST['password']);

  $sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
  $result = mysqli_query($db, $sql);

  // 处理查询结果
}

In the above code, we have usedaddslashesThis function escapes special characters in the input string, making it safe to use when constructing SQL statements. Note that,addslashesFunctions have certain limitations; in some cases, they may not fully prevent SQL injection attacks. Therefore, they are not recommended as the sole means of defending against 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

(Adaptive mobile version) Heavy Industry Machinery & Equipment Website – PBootCMS Template; Download General Website Source Code for Crane and Lifting Machinery – 0410

(Adaptive mobile version) Heavy Industry Machinery & Equipment Website – PBootCMS Template; Download General Website Source Code for Crane and Lifting Machinery – 0410 Practical Collection pbootcms Template

An adaptive mobile website template for heavy-duty machinery and crane equipment, built with PbootCMS. The professional industrial design is ideal for showcasing lifting equipment, cranes, and related products as well as engineering applications. This template helps heavy machinery manufacturers showcase their brands online and attract industrial and construction clients. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn...
👁 37
Environmental Protection New Materials & New Energy Recycling Website Template – 0731

Environmental Protection New Materials & New Energy Recycling Website Template – 0731 Practical Collection Yiyou template

This EyouCMS template is ideal for enterprises specializing in eco-friendly new materials or new energy recycling. Its green technology design style is perfect for showcasing innovative environmental materials, energy recovery technologies, and related products. It helps environmental protection companies build a strong green brand image online and attract potential partners. Template Demo | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 50
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 version) Desulfurization equipment website template; Pressure vessel website source code download – 1145

(Adaptive mobile version) Desulfurization equipment website template; Pressure vessel website source code download – 1145 Practical Collection pbootcms Template

A desulfurization equipment and pressure vessel website template compatible with both PC and WAP devices. The professional industrial design is ideal for showcasing desulfurization equipment, pressure vessel products, and project cases. It enables environmental protection equipment manufacturers to showcase their products online and attract clients from the power and chemical industries. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn...
👁 60
(Adaptive mobile version) Metal products – Metal mesh filters and screens; PBootCMS website template; Download source code for a black-themed corporate website for metal manufacturing companies – 0411

(Adaptive mobile version) Metal products – Metal mesh filters and screens; PBootCMS website template; Download source code for a black-themed corporate website for metal manufacturing companies – 0411 Practical Collection pbootcms Template

This set includes an adaptive mobile-friendly metal products and metal mesh filter screen website template for the PbootCMS platform. The design features a sleek black aesthetic, making it ideal for showcasing metal products, industrial filters, and precision-machined components. It helps metal manufacturing enterprises demonstrate their manufacturing expertise online and attract industrial clients. Template Overview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn...
👁 40
Responsive exhaust gas treatment environmental protection equipment website template – 0732

Responsive exhaust gas treatment environmental protection equipment website template – 0732 Practical Collection Yiyou template

An eyouCMS responsive website template designed for environmental protection equipment manufacturers specializing in exhaust gas treatment systems. Its modern, eco-friendly design is ideal for showcasing exhaust gas treatment equipment, technical solutions, and project cases. This template helps environmental engineering firms present their solutions online and attract both industrial and municipal clients. Template Overview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Common Installation Questions for YououCMS...
👁 35