Question

I'm putting together a registration/login form in PHP using Netbeans. To implement this, I have my login, registration and database connection functionality in a scripts.php file, which is loaded via an include call.

Well, my login function uses this

$username = mysql_real_escape_string($_POST['username']);
$password = sha1(mysql_real_escape_string($_POST['password']));
$query = sprintf("SELECT * FROM users WHERE username='%s' AND password='%s'", $username, $password);

$link = connectDB();

$results = mysqli_query($link, $query);

to connect to the db and get the results. Validation happens later on.

For my registration logic, I use almost the same thing:

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

//check if user name and password match conditions
$link = connectDB();
$query = "SELECT * FROM users WHERE username = '" . $username . "'";
$results = mysqli_query($link, $query);

The registration page loads fine, but the login page has an error text printout saying that there is an undefined index 'username' in the login function. This occurs as the page loads, and no functions have been called.

However, with almost the same layout in the registration function, I don't get the error.

Why is this occuring?

EDIT

I found the issue.

I was opening the database connection using mysqli_connect, but using the mysql-real_escape_string function. The two are incompatible, and adding the i made all the different.

Was it helpful?

Solution

Several points, which may or may not be related to your question but that I simply cannot overlook:

  1. SQL-escaping a string is always the last thing that happens. Don't SQL-escape a string, then sha1 it. See The Great Escapism to learn what escaping is all about.
  2. When using mysql_real_escape_string, you need to connect to the database first before calling this function, since it needs to have an established database connection to do its job.
  3. You are mixing the mysql and mysqli extensions. Use one or the other, not functions of both.
  4. If you're using mysqli (and you should!), use prepared statements instead of manually SQL-escaping the string and sprintf.

In other words, currently you are doing it entirely wrong. Fix those things first and your problem may go away with it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top