Reputation: 11
I am working on a site where I am fetching records from database to match with the user input, if the data does not match with the details in database it must show an javascript alert box. But the problem is the javascript box is showing on body load too. Following is my code :
//Storing the value of form's username and password into PHP variables
$username = $_POST['username'];
$password = $_POST['password'];
//This query is to check whether ther user has provided valid details
$query = mysql_query("Select * from accounts where username='$username' and password='$password'");
$status = mysql_num_rows($query);
/**Now checking whether the number of rows returned by database are greater than 0 to verify the login
if number of rows are greater than zero we will redirect the user to index page with a session variable**/
if($status >0)
{
$_SESSION['username'] = $username;
?>
<meta http-equiv="refresh" content="0;url=index.php">
<?}
else
{?>
<script language="javascript">
alert('UserName or Password does not match. Please try again');
</script>
<?}?>
Upvotes: 0
Views: 1181
Reputation: 11
you miss <?php and Varible
this Code Use then Check
<?php
$username = $_POST['username'];
$password = $_POST['password'];
//This query is to check whether ther user has provided valid details
$query = mysql_query("Select * from accounts where username='".$username."' and password='**".$password."**'");
$status = mysql_num_rows($query);
/**Now checking whether the number of rows returned by database are greater than 0 to verify the login if number of rows are greater than zero we will redirect the user to index page with a session variable**/
if($status >0)
{
$_SESSION['username'] = $username;
?>
<meta http-equiv="refresh" content="0;url=index.php">
**<?php** }
else
{?>
<script language="javascript">
alert('UserName or Password does not match. Please try again');
</script>
**<?php** }?>
Upvotes: 0
Reputation: 382102
Replace
else
with
else if (isset($_POST['username'])) {
if you don't want the alert to appear when the user isn't trying to log in.
Upvotes: 1
Reputation: 15616
You need a login flag for this.
Add this to your form:
<input type="hidden" name="login_process" value="true" />
and then surround your login code with:
if($_POST["login_process"] == "true"){
//your login code
}
...your page body
Upvotes: 0