Asked By
jcwood
0 points
N/A
Posted on - 04/13/2012
Hello there web experts!
I really need your help on this problem.
I am a newbie to web programming especially PHP and I just started making a sample website to test what I have learned.
I have there on my database a table called account and the columns there are username and password.
How can I check in my database if the input username and password is correct.
What are the php codes for this guys?
Thanks.
PHP Code for checking username and password
Dear friend
Below Login check script will help to check username and password from DB table and if username and password are correct you can redirect to your homepage and start session.
require("connection.php");
$sql=mysql_query("select * from account where username='$_POST[txt_name]' and password='$_POST[txt_password]'");
//query to check entered username and password.
$num_rows=mysql_num_rows($sql);
//if no row found it return 0 otherwise no of row.
if($num_rows>0)
{
$rs=mysql_fetch_array($sql);
//fetch record from table
session_start();
//start session
$_SESSION['username']=$rs['username'];
//set session variable to track session.
 header("Location:homepage.php");
//Successful login redirection page
}
else
{
   header("Location:loginvarify.php");
   //redirect to page when wrong username and password entered.
}
 mysql_close($con);
 mysql_free_result($sql);
?>
PHP Code for checking username and password
<?php
//Create a session
session_start();
//Make a connection to the database
$dbh=mysql_connect ("localhost", "username_of_database", "password") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("database_name");
$user="";
$password="";
//Retrieve the form elements values
if (isset($_POST['user'])) //user is a field in form
 $user = $_POST['user'];
if (isset($_POST['password'])) //password is a field in form
{
 $password = $_POST['password'];
}
//If login is not blank retrieve user information
if($user!="" || $password !="")
{
$query ="SELECT * FROM user WHERE user_id='".$user."' AND pass='".$password."'";
$result = mysql_query($query, $dbh);
$affected_rows =mysql_num_rows($result);Â //count number of rows
//If match found then login succeeded. Set session
if ($affected_rows==1)
{
 $_SESSION['user'] = $user;
 print "<center>Login successful.</center>";
}
else
{
//If match not found, inform the user
 print "<center><font color=red>Incorrect username or password. Try again.</font></center>";
}
}
else
{
 print "<center><b>Please Login</b></center>";
}
?>