Escaping Strings
suggest changeEscaping strings is an older, less safe way to put data into a query. mysqli_real_escape_string() escapes a string for the connection’s character set. It does not add quotes, and it does not make an unquoted value safe.
$escaped = $conn->real_escape_string($_GET['var']);
// OR
$escaped = mysqli_real_escape_string($conn, $_GET['var']);
At this point, you have a string that MySQL considers to be safe for use in a direct query
$sql = 'SELECT * FROM users WHERE username = "' . $escaped . '"';
$result = $conn->query($sql);
Prepared statements are safer. See prepared statements. Escaping does not change 1 OR 1=1, and this query never quotes the value:
$id = mysqli_real_escape_string($conn, "1 OR 1=1");
$sql = 'SELECT * FROM table WHERE id = ' . $id;
The result is still WHERE id = 1 OR 1=1. A wrong connection charset can also defeat escaping. This write-up shows one case. The function makes a string a legal SQL string literal. It does not decide where that literal is allowed to appear.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents