3

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. :)

elixenide
  • 44,308
  • 16
  • 74
  • 100
Francisco F.
  • 111
  • 1
  • 3
  • 14

1 Answers1

4

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.

Community
  • 1
  • 1
elixenide
  • 44,308
  • 16
  • 74
  • 100
  • I tried using mysqli and it still didn't work. I did `mysqli_real_escape_string($_POST['username']);` and still nothing. – Francisco F. Jan 22 '17 at 03:43
  • 1
    @FranciscoF. Pay attention to the arguments: `string mysqli_real_escape_string ( mysqli $link , string $escapestr )`. The first argument, in your case, should be `$db`. So, the actual line is `$username = mysqli_real_escape_string($db, $_POST['username']);`. – elixenide Jan 22 '17 at 03:44
  • 1
    So it would be `mysqli_real_escape_string($db, $_POST['username'])`? – Francisco F. Jan 22 '17 at 03:50
  • As @EdCottrell recommended, look into prepared statements, then you won't need to use escape string. – Thomas Jan 22 '17 at 04:38