PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Hey all,
This PHP newb has finally created his own php/mysql news script! ::Pats self on back:: So anyway, all is well with it besides checking to see if the user put in the right password.
Here's the code:
<?PHP
mysql_connect("localhost","---","---");
mysql_select_db("users");
$getuser = mysql_query("SELECT * FROM userinfo WHERE
username='$user'");
While($rows = mysql_fetch_array($getuser)) {
$username = $rowsїusername];
$password = $rowsїpassword];
}
mysql_close();
If($user == $username && $pass == $password) {
mysql_connect("localhost","---","---");
mysql_select_db("news");
$insert = "INSERT INTO posts VALUES
('$id', '$user', '$title', '$date', '$time', '$body')";
mysql_query($insert);
echo "Successfully posted! ---> <A Href="news.php">Click to go to news.php</a>";
mysql_close();
}
else {Echo "Sorry, It looks like you've entered the wrong username
and/or password";}
?>
It works fine when A)Someone doesn't enter a username, but enters a password, B) When someone enters a password and not a username, and C) When someone enters a username that doesn't exist. That just leaves out one thing. When someone doesnt enter a username OR a password, the if() statement equals true and go's ahead and posts. Why is this? Can anyone give me some pointers on correcting this?
$query = "SELECT * FROM userinfo WHERE username='$user' AND password='$pass'";
$getuser = mysql_query($query) or die(mysql_error());
if ( $rows = mysql_fetch_array($getuser)) )
// login successful
else
// login failed
let mysql do the work
besides: unless you defined a constant username replace $username = $rows[username]; by $username = $rows['username'];
or you will get a Notice: Use of undefined constant username - assumed 'username' in whatever.php on line xyz
Well I'm not sure.. because when neither the $pass text box nor the $user text box were filled in, it still posted..And if neither had a value, therefor making them not equal to $username or $password, that line would stop it from posting, wouldn't it?
Maybe I'll use the mysql WHERE clause..I'm still trying to get the hang of things as far as php/mysql go.
when a SELECT-query has been successful there is a resultset for this query that can contain 0 to N records.
You retrieve those records one by one e.g. with mysql_fetch_array.
If there is no recordset left mysql_fetch_array will return FALSE.
So if ($rows = mysql_fetch_array($getuser)) !== FALSE there was a recordset with the give user/password-combination.
If there is no such recordset the query will be successful, too (hopefully) but mysql_fetch_array will return FALSE and the if-clause fails --> no login