phpsqldatabasemysql-real-escape-string

mysql_real_escape_string not working for me


When I try to do a mysql_real_escape_string for a login system, it does not record the variable from the form. If I do

$username = $_POST['username'];

and echo it, it displays, but when I do

$username = mysql_real_escape_string($_POST['username']);

and echo it, it does not display. I also tested the database connections, and they work. This is my code:

session_start();
$db = mysqli_connect($connection, $user, $pass, $database);
if (isset($_POST['submit'])) {
    $username = mysql_real_escape_string($_POST['username']);
    $password = mysql_real_escape_string($_POST['password']);
    echo $username;

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

It used to work before, but for some reason it stopped working suddenly. Any help is appreciated. :)


Solution

  • First, you shouldn't be escaping data to build queries. You should be using prepared statements. See How can I prevent SQL injection in PHP?

    That said, your problem is that you're using mysql_real_escape_string(), but you have a mysqli (not mysql) connection. mysqli and mysql are different extensions. Please don't use mysql_*; the mysql_* functions are outdated, deprecated, and insecure - they have been removed entirely from modern versions of PHP (version 7.0 and higher). Use MySQLi or PDO instead.

    To fix your problem temporarily, use mysqli_real_escape_string() instead of mysql_real_escape_string(). To fix it permanently and correctly, use prepared statements and not escaping.