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!