Is the code below better at preventing a SQL injection on a MySQL database than mysqli_real_escape_string would be?
$str = "SELECT * FROM customers WHERE username = '; DELETE FROM customers WHERE 1 or username = '";
$str2 = "";
for($i = 0; $i < strlen($str); $i++)
{
if (strpos ("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ,.?!0123456789", $str[$i], 0) !== FALSE)
{
$str2 = $str2 . $str[$i];
}
}
echo "$str2";
There is absolutely no reason to use a whitelist/blacklist when trying to avoid SQL injection. All you need to do when using the
mysqli_functions without prepared statements is to process data withmysqli_real_escape_string().However, you’d be better off learning about prepared statements instead. They are cleaner and safer than escaping.
The code to execute your example query with prepared statements would look like this:
Since you don’t understand the example, here’s a detailed explanation:
?whenever you want to use external data.s) parameter for the first placeholder. So$usernameshould contain the (untrusted) value