Home >Backend Development >PHP Tutorial >Does `mysqli_real_escape_string` Offer Complete Protection Against SQL Injection?

Does `mysqli_real_escape_string` Offer Complete Protection Against SQL Injection?

Linda Hamilton
Linda HamiltonOriginal
2024-12-20 03:02:13643browse

Does `mysqli_real_escape_string` Offer Complete Protection Against SQL Injection?

Can "mysqli_real_escape_string" Fully Prevent SQL Injection?

Consider the following example code:

$email = mysqli_real_escape_string($db_con, $_POST['email']);
$psw = mysqli_real_escape_string($db_con, $_POST['psw']);

$query = "INSERT INTO `users` (`email`,`psw`) 
           VALUES ('" . $email . "','" . $psw . "')";

Is this code secure against SQL injection and other attacks?

Answer: No.

As highlighted in the provided code examples, "mysqli_real_escape_string" alone is insufficient to guarantee protection against SQL injection. Attackers can exploit vulnerabilities in its implementation to bypass filtering and compromise the application.

Recommended Solution:

The most effective way to prevent SQL injection is to use prepared statements. Prepared statements isolate data from SQL queries, ensuring that no external inputs interfere with the query structure. Additionally, consider implementing a strict whitelist to filter data specifically for its intended purpose. This approach minimizes the risk of SQL injection and other security vulnerabilities.

Example of a Secure Query Using Prepared Statements:

$stmt = $db->prepare(
    "SELECT * FROM table 
    WHERE col = ? ORDER BY {$sortby} ASC 
    LIMIT ?, ?"
);
$stmt->execute(['value', $start, $howmany]);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

By incorporating these measures, you can significantly enhance the security of your SQL operations against malicious attacks.

The above is the detailed content of Does `mysqli_real_escape_string` Offer Complete Protection Against 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