3

I am currently upgrading code for a friends website and have encountered a problem with the login script. I'm trying to prevent SQL Injection by using mysql_real_escape_string(). mysql_escape_string() works fine but mysql_real_escape_string() doesn't. This is what I've got:

if (isset($_POST['submit']))
{
    $username = mysql_real_escape_string($_POST['username']); 
    $password = mysql_real_escape_string($_POST['password']);

    $db_link = db_connect("project");
    $query = "SELECT * FROM user WHERE username = '$username' AND password = password('$password')";
    $result = mysql_query($query) or die (mysql_error());
    $numrows = mysql_num_rows($result);

    if($numrows == 1)
    {
        RedirectToURL("home.php");
    }
    else
    {
        login_page("Invalid login! Try again");
    }   
}
else
{
    login_page("");
}
JCOC611
  • 19,111
  • 14
  • 69
  • 90
user1798578
  • 221
  • 3
  • 12

2 Answers2

6

In order to use mysql_real_escape_string you have to be logged in to the database. If you are not logged in, then use mysql_escape_string.

Lior
  • 5,841
  • 9
  • 32
  • 46
2

As @MichaelBerkowski said in your comment, move the mysql_real_escape_string() calls past your connection command:

if (isset($_POST['submit']))
{

    $db_link = db_connect("project");

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

    $query = "SELECT * FROM user WHERE username = '$username' AND password = password('$password')";
    $result = mysql_query($query) or die (mysql_error());
    $numrows = mysql_num_rows($result);

    if($numrows == 1)
    {
        RedirectToURL("home.php");
    }
    else
    {
        login_page("Invalid login! Try again");
    }   
}
else
{
    login_page("");
}

The reason, as told above, is that mysql_real_escape_string() depends on your mysql connection to work

Sergi Juanola
  • 6,531
  • 8
  • 56
  • 93