Login Script with PHP/MySQL

He has: 296 posts

Joined: May 2002

I already have it written, but it doesn't work. I get an "Invalid MySQL Resource" error on line 15. Here is the code for the login script:

<?php
$connect
= mysql_connect('localhost','USER','PASS');
$selectdb = mysql_select_db('DB',$connect);

if (!
$connect) {
  echo (\
"Cannont connect to the database at this time. Please try at a different time.\");
}

if (!
$selectdb) {
  echo (\"Cannont reach to the database at this time. Please try at a different time.\");
}

$query = mysql_query(\"SELECT * FROM users WHERE user=$username\");
  while (
$arow = mysql_fetch_array($query)) {  //LINE 15
   
$pass = $arow[\"password\"];
   
$user = $arow[\"user\"];

  if (
$password != $pass) {
    echo (\"Invalid password, please go back and fix it.\");
  }

  if (
$usernamer != $user) {
    echo (\"Invalid username, please go back and fix it.\");
  }

  if (
$username == $user && $password == $pass) {
    echo (\"You logged in! Your username is
$user and your password is $pass.\");
  }
}
?>

here is the page that has the forms:

<?php
<html>
<
body>

  <
form method=\"post\" action=\"login.php\">
  Username:<input type=\"Text\" name=\"username\"><br><BR>
  Password:<input type=\"Text\" name=\"password\"><BR><BR>
  <input type=\"Submit\" name=\"submit\" value=\"Login\">
  </form>

</body>
</html>
?>

Tell me if you need anything else.

[James Logsdon]

mairving's picture

They have: 2,256 posts

Joined: Feb 2001

On line 14, try changing this:
$query = mysql_query("SELECT * FROM users WHERE user=$username");
to
$query = mysql_query("SELECT * FROM users WHERE user='$username' ");

Mark Irving
I have a mind like a steel trap; it is rusty and illegal in 47 states

He has: 296 posts

Joined: May 2002

Thanks! It works now! I hate how tiny things like that can totally screw up your script. It's still a little buggy, but you can check it out here. Login: test pass: test

[James Logsdon]

Abhishek Reddy's picture

He has: 3,348 posts

Joined: Jul 2001

If I enter a random username, I don't get a "Invalid Username" error. Most probably because of this:

<?php
 
if ($usernamer != $user) {
    echo (\
"Invalid username, please go back and fix it.\");
  }
?>

Change usernamer to username. Smiling

He has: 296 posts

Joined: May 2002

O god, stupid typos. Thanks for noticing that:)

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.