I want my code to check if the username and password exist in my database. It does work hardcoded, but I want to do it with a database.Right now this is what I have:
You can use mysql_num_rows() and combine your query - See footnotes
if(isset($_POST["name"], $_POST["password"]))
{
$name = $_POST["name"];
$password = $_POST["password"];
$result1 = mysql_query("SELECT username, password FROM Users WHERE username = '".$name."' AND password = '".$password."'");
if(mysql_num_rows($result1) > 0 )
{
$_SESSION["logged_in"] = true;
$_SESSION["naam"] = $name;
}
else
{
echo 'The username or password are incorrect!';
}
}
In order to make your present code a bit more secure, use:
$name = stripslashes($_POST["name"]);
$name = mysql_real_escape_string($_POST["name"]);
$password = stripslashes$_POST["password"]);
$password = mysql_real_escape_string($_POST["password"]);
but do look at the links below about using prepared statements and password hashing.
Footnotes:
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements. Visit those links for more information.
I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.
If you are and this is a LIVE site, you will eventually get hacked.
I recommed you use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
Edit: to help out OP (do look into the links I've provided concerning password hashing).
Try replacing
if(mysql_num_rows($result1) > 0 )
{
$_SESSION["logged_in"] = true;
$_SESSION["naam"] = $name;
}
else
{
echo 'The username or password are incorrect!';
}
with:
while($row=mysql_fetch_assoc($result1))
{
$check_username=$row['username'];
$check_password=$row['password'];
}
if($username == $check_username && $password == $check_password){
echo "Matches.";
}
else{
echo "No match found.";
}