I am making a simple user update page where the user can update the password and their email, but I want to do it with two separate forms, because if I use one, and sent one of the field empty, it will update it to empty in the database. (And I want the user to be able to update only email or only username).
Here is my code:
<html>
<body>
<?php
$con=mysqli_connect();
session_start();
if (!isset($_SESSION['ID'])){
header('location:login.php');
}
//
?>
<?php
if(!isset($_POST['submit'])) {
$con=mysqli_connect();
} else {
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
?>
<?php
$email = mysqli_real_escape_string($con,$_POST['Email']);
$password = mysqli_real_escape_string ($con,$_POST['Password']);
$ID = $_SESSION['ID'];
$emailErr = $passwordErr="";
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Please enter a valid Email Address";
}
else {
$sql="UPDATE `customer`
SET `Email`='$email'
WHERE `ID`='$ID'";
$result = mysqli_query($con,$sql);
echo "Update complete!";
//header("Location: userpage.html");
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
}
}
?>
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?> method="post"><br />
Email:<br /> <input type="text" name="Email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span><br /><br />
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (!preg_match("/^[a-zA-Z0-9#_]*$/",$password))
{
$passwordErr = "Please enter a valid password";
}
else {
$sql="UPDATE `customer`
SET `Password`='$password'
WHERE `ID`='$ID'";
$result = mysqli_query($con,$sql);
echo "Update complete!";
//header("Location: userpage.html");
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
}
}
mysqli_close($con);
?>
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?> method="post"><br />
Password:<br /> <input type="password" name="Password">
<span class="error">* <?php echo $passwordErr;?></span><br /><br />
<input type="submit">
</form>
</body>
</html>
With this code if I update the second form (which is the password) I will get an error for the first one, because it executes on submit.
How can I make it so that I have two forms on the same page that update different rows in the table on clicking the submit button, without redirecting to a different page?
Thank you
You could give each submit (or other input) a unique name, and check if it's set after POSTing
For example, give your submit button a name:
<input type="submit" name="turtle">
And in your PHP:
<?php
if(isset($_POST['turtle'])) {
// Process the form associated with the "turtle" submit button.
} else {
// Do the other form stuff.
}
?>
Why don't you combine into one form and check if the user has entered a password?
<?php
$con = mysqli_connect();
session_start();
if (!isset($_SESSION['ID'])){
header('location:login.php');
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST['submit'])):
$email = mysqli_real_escape_string($_POST['Email']);
$password = mysqli_real_escape_string($_POST['Password']);
$ID = $_SESSION['ID'];
// Validate Email
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email)) {
$errors[] = "Please enter a valid Email Address";
}
// Check if the password field has been filled in
if($password) {
// If it has then do your regex...
if (!preg_match("/^[a-zA-Z0-9#_]*$/",$password)) {
$errors[] = "Please enter a valid password";
$update_password = false;
} else {
$update_password = true;
}
}
if(count($errors) == 0) {
// Update Email
$sql="UPDATE `customer`
SET `Email`='$email'
WHERE `ID`='$ID'";
$result = mysqli_query($con,$sql);
// If the test above passed then update the password
if($update_password) {
$sql="UPDATE `customer`
SET `Password`='$password'
WHERE `ID`='$ID'";
$result = mysqli_query($con,$sql);
}
echo 'Update Complete';
//header("Location: userpage.html");
}
?>
<?php else: ?>
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?> method="post"><br />
<?php if($errors): ?>
<span class="error">* <?php echo explode(', ',$errors);?></span><br /><br />
<?php endif; ?>
Email:<br /> <input type="text" name="Email" value="<?php echo $email;?>">
Password:<br /> <input type="password" name="Password">
<input type="submit" name="submit">
</form>
<?php endif; ?>
P.S I tidied up your code as it gave me a hernia.
Use hidden inputs to seperate requests
OR
Use seperate files for your different forms as targets...
OR
Use jboneca's answer
Related
I have this script sign in first with sql insert into query and redirected to login page. I checked all my queries on phpmyadmin. All queries are working. I do not have any error message in my query. Also it is suppose to show " password/username does not match" message if there is incorrect user/password. After i submit form, the page did not redirect to welcome page and form field clears.
this is my login page
<?php
require_once "./include/variables.inc.php";
$debug =0;
$error_text = "";
$uname = "";
$pwd = "";
session_start();
if (!isset($_SESSION['member_id'])){
if(isset($_POST["submit"])) {
if($debug) {
echo "<pre>";
print_r($_POST);
echo "</pre>";
//die("temp stop point");
}//end ofdebug if
$uname = mysqli_real_escape_string($dbc,trim($_POST['uname']));
$pwd = mysqli_real_escape_string($dbc,trim($_POST['pwd']));
if (!empty($uname) && !empty($pwd)) {
$query = "SELECT * FROM employees WHERE username = '".$uname."'
AND password = '".MD5($pwd)."'";
echo $query;
$result = mysqli_query($dbc,$query) or die ("Error in query". mysql_error());
if(mysqli_num_rows($result)) {
$row = mysqli_fetch_assoc($result);
$_SESSION['member_id'] = $row['member_id'];
$_SESSION['member_name'] = $row['member_name'];
header('Location:index.php');
}
else {
$error_text .= "The username/password are incorrect. Please enter correct username and password.";
}
}
}//end of if(isset($_POST["submit"])
}
require_once('./include/html.head.php');
?>
<body>
<div id="wrapper">
<?php require_once('./include/header.php'); ?>
<div id="side">
<?php require_once('./include/pb.side.php'); ?>
</div>
<div id="content">
<div class="form">
<p class="strong">All Santa helpers log-in here.</p>
<?= $error_text ?>
<form method="post" action="<?= $_SERVER['PHP_SELF'] ?>" enctype="multipart/form-data">
<p>User Name: <input name="uname" type="text" value="<?= $uname ?>"></p>
<p>Password: <input name="pwd" type="password"></p>
<input name="submit" type="submit" value="Login">
</form>
</div>
<div class="rdeer">
<img src="images/login_img.png" alt="Rain Deer">
</div>
</div>
<?php require_once('./include/footer.php'); ?>
</div>
</body>
</html>
and function php is
<?php
function user_authenticated($username, $password) {
if(!empty($username) && !empty($password)) {
$query = "SELECT userName, password FROM employees WHERE userName = '".$username."' and password = '".$password."'";
$result= mysqli_query($dbc, $query)
or die ("Query does not work." . mysql_error());
// If result matched $username and $password, table row must be 1 row
} else {
echo "Query error. ";
}
}
Notice the line mysqli_num_rows($result). Replace it with mysqli_num_rows($result)>0 since that function returns an int.
I've been working on a website login, and so far, I have the database and register page set up, but I'm trying to work on a Login page. I've been trying to retrieve data from the Database's Table. I was successfull at doing so on my register page to make sure there aren't multiple usernames of the same name, so I copied some of the code and pasted it onto this page. The problem: it returns blank. Please help... ._.
`
KHS SiteSpace
<div id="header">
<img src="./IMAGES/khslogo2.png" style="margin-left:4;float:left;" width="100" hieght="100">
<b>KHS<span id="name">SiteSpace</span></a>
<!--img src="./IMAGES/Menu.png" style="float:right;margin-right:6;" height="100" width="90"-->
</div>
<div id="content">
<p id="subTitle">Login</p>
<div style="float:left;height:30%;">
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" id="register"><br>
Username:<br>
<input type="text" name="name"><br><br>
Password:<br>
<input type="password" name="pass">
<br><br>
<input type="submit" value="Confirm">
</form>
</div>
<div style="float:right;width:50%;border-style:none none none solid; border-color:222222;border-width:4;height:30%;">
<p style="margin-left:20;font-size:20;">Output:</p>
<p style="margin-left:20;padding-bottom:15;">
<?php
error_reporting(0);
#ini_set('display_errors', 0);
session_start();
$conn = new mysqli("localhost", "shanedrgn", "getting321", "Users");
if (!$conn) {die("Failure to connect");}
$name = trim($_POST['name']);
$pass = trim($_POST['pass']);
if (empty($name) or empty($pass)) {echo "Empty Fields";} else {
$name = trim($_POST['name']);
$pass = trim($_POST['pass']);
echo "Check: The fields arent empty...";#OUTPUT
echo "Testing Variables...";#OUTPUT
//Error Trapping
$sql = "SELECT Username FROM Users where Username = '$name'";
$Data = mysqli_query($conn, $sql);
if($record=mysqli_fetch_array($Data)) {
$nameTrap = $record['Username'];
}
$sql = "SELECT Address FROM Users where Address = '$address'";
$Data = mysqli_query($conn, $sql);
if($record=mysqli_fetch_array($Data)) {
$ipTrap = $record['Address'];
}
if ($nameTrap == $name) {
echo "Check: Username Exists...";
if ($passTrap == $pass) {
echo "Password is correct!";
$_SESSION['User'] = $name;
$sql = "SELECT * FROM Users where Username = '$name'";
$Data = mysqli_query($conn, $sql);
$record=mysqli_fetch_array($Data);
session_start();
$_SESSION['id'] = $record['id'];
echo "<script>alert('You have successfully logged in!')</script>";
sleep(4);
header("Location: ./index.php"); /* Redirect browser */
exit();
} else { echo "Password Invalid";}
} else {echo "That username doesn't exist!";echo $name.";;";echo $nameTrap;}
}
?>
</p></div>
</div>
</body>
</html>`
EDIT: Added missing code
You are doing this:
echo "<script>alert('You have successfully logged in!')</script>";
sleep(4);
header("Location: ./index.php"); /* Redirect browser */
I understand, what you try, but it can't work. You can't set an Header after sending Body-Content - what you do using echo.
You should use JavaScript for your redirect, after the 4 second timeout. Use setTimeout and window.location.
// php code start------------->
<?php
// define variables and set to empty values
$nameErr=$empidErr=$usernameErr=$passwordErr="";
$name=$empid=$username=$password="";
if(isset($_POST['submit']))
{
if (empty($_POST["empid"])) {
$empid = "";
} else {
$empid = test_input($_POST["empid"]);
}
if (empty($_POST["name"])) {
$name = "";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["etype"])) {
$etype = "";
} else {
$etype = test_input($_POST["etype"]);
}
if (empty($_POST["username"])) {
$usernameErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
// check if name only contains letters and whitespace
if (!preg_match("/[0-9A-Za-z ^-_#. ]*$/",$username)) {
$usernameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password = test_input($_POST["password"]);
// check if name only contains letters and whitespace
if (!preg_match("/[0-9A-Za-z ^-_#. ]*$/",$password)) {
$passwordErr = "Only letters and white space allowed";
}
}
}
//collect the data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if((strlen($name)>0)&&(strlen($empid)>0)&&(strlen($etype)>0)&&(strlen($username)>0)&&(strlen($password)>0))
{
include "connection.php";
//Here to check the username is aleady present in database or not
$query = mysql_query("SELECT * FROM signin WHERE username='$username' ", $con);
//$result = mysql_query($query) or die('Error: ' . mysqli_error($con));
if (mysql_num_rows($query) <=0)
{
echo "<script>alert('User already Exists Change the username');</script>";
echo"<script>window.location.href = 'signin.php';</script>";
}
else
{
//if not present in database then create the new user in database.
$sql="INSERT INTO signin (emp_name,emp_id,emp_type,username,password,create_datetime)
VALUES ('$name','$empid','$etype','$username','$password',now())";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "<script>alert('New User Added Successfully');</script>";
echo"<script>window.location.href = 'login.php';</script>";
}
mysqli_close($con);
}
?>
//php code end------------<
//html code------------------>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<legend> <b><i> Information</i></b></legend><br>
Employee ID:-<input type="text" name="empid" placeholder="Enter Employee ID" size="10" value="<?php echo $rum1?>" readonly>
Employee Name:-<input type="text" name="name" placeholder="Surname Middlename Father Name" size="50" value="<?php echo $rum2;?>" readonly>
Employee Type:-<input type="text" name="etype" placeholder="Type" value="<?php echo $rum3;?>" readonly><br /><br />
Username:-<input type="text" name="username" id="loginid" placeholder="Username" size="30" value="<?php echo $unm;?>">
<span class="error">* <?php echo $usernameErr;?></span> <br /><br />
Password:-<input type="password" id="password" name="password" size="30">
<span class="error">* <?php echo $passwordErr;?></span> <br />
</fieldset>
<br>
<input name="submit" type="submit" value="Submit">
<input name="reset" type="submit" value="Reset">
<br ><br >
</form>
</fieldset>
</body>
</html>
//html code end---------------------<
In above php code is work but i want to check username.if the username present in the database then give the alert as the user is already present in the database change the username please. So please sir or madam suggest any code or changes in this php code and suggest any solution to check the user present in database or not.if user first time register then new user is added and if user multiple second time register then give alert is user already register please do your login.
to know if present mysql_num_rows should return 1 or special cases more than one
so change this
if (mysql_num_rows($query) <=0)
{
echo "<script>alert('User already Exists Change the username');</script>";
echo"<script>window.location.href = 'signin.php';</script>";
}
To this
if (mysql_num_rows($query) >0)
{
echo "<script>alert('User already Exists Change the username');</script>";
echo"<script>window.location.href = 'signin.php';</script>";
}
Dont use mysql function as they are depriciated. Learn mysqli or PDO
My class is attempting to make our own game.. But, we can't get the submit page to send to the database in PhpMyAdmin. When you click submit, it sends blank entries to the database, like if you hadn't filled in any of the blanks. Can someone help with this problem. Thanks!!
My index.php page.
<html>
<head>
<meta charset="UTF-8">
<title> Register New Account </title>
<link rel="stylesheet" type="text/css" href="td.css">
</head>
<body>
<?php
/* $count=$count+1;
echo " count " . $count; */
if($_POST['submit_id'] == 1)
{
/* echo "testing"; */
if($_POST['Username'] == NULL)
{
$message = 'Please enter your Username.';
}
if($_POST['Email'] == NULL)
{
$message = 'Please enter your Email.';
}
if($_POST['Confirm'] == NULL)
{
$message = 'Please re-enter your Email.';
}
if($_POST['Password'] == NULL)
{
$message = 'Please enter your Password.';
}
if($_POST['Email'] != $_POST['Confirm'])
{
$message = 'Your emails did not match, Please enter your emails again.';
}
}
if( $message == NULL )
{
// if there is no error, test to see if there is already an account by the player_name
$MySQLlink = new mysqli("localhost", "root", "******", "Tower_Defense");
// check connection - take out later
if ( !$MySQLlink )
{
printf( "Could not connect to MySQL server : %s", mysqli_connect_error() );
exit();
}
else
{
printf( "Connected to the MySQL server" );
echo "<br>";
}
$result = mysqli_query( $MySQLlink, "SELECT * FROM Users WHERE ( email = 'email' ) " );
if($row = mysqli_fetch_array($result))
{
$message = "There is an account with that email address already. Please choose another email account";
}
mysqli_free_result($result);
$result = mysqli_query( $MySQLlink, "SELECT * FROM Users WHERE ( Username = '$Username' ) " );
if( $row = mysqli_fetch_array($result) && $message == NULL )
{
$message = "There is an account by that player name already. Please choose another Login name";
mysqli_free_result($result);
}
else
{
//echo "next date <br>";
// create account
$Username = ($_POST['Username']);
$Password = ($_POST['Password']);
$Email = ($_POST['Email']);
$email = ($_POST['email']);
//echo "Next one<br>";
$TableList = " `Username`, `Password`, `Email`, `Confirm` ";
$Values = " '$Username', '$Password', '$Email', '$Confirm' ";
if($message != NULL)
{
echo "$message";
}
?>
<div id="container" >
<div id="header">
<h1 id="h1">Besco's Biscuits</h1>
About
Instructions
The Creation Of The Game
Contact Us
</div>
<br /> <br /> <br />
<table align = "center">
<tr>
<td>
Welcome to <b> Besco's Biscuits </b>. Please fill out the following <br />
areas and we will begin your adventure soon. :)
</td>
</tr>
</table>
<br /> <br /> <br /> <br /> <br />
<table align = "center">
<tr>
<td>
<form action = "<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post"> <br />
Username: <input type="text" name="Username" id= "Username"> <br />
Email: <input type = "text" name = "Email" id= "Email"> <br />
Confirm: <input type = "text" name = "Confirm" id= "Confirm"> <br />
Password: <input type = "password" name = "Password" id = "Password"> <br />
<input type = "submit" value = "Register" id="submit_id" value = "1">
<input type = "reset" name="Reset" value="Check if Available!" class = "account">
</form>
</td>
</tr>
</table>
</body>
</html>
My insert.php page
<html>
<body>
<?php
$Username = $_POST['name'];
$con=mysqli_connect("localhost", "root", "******", "Tower_Defense");
//Check Connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Users (Username, Email, Confirm, Password)
VALUES
('$_POST[Username]','$_POST[Email]',' $_POST[Confirm]',' $_POST[Password]')";
if (!mysqli_query($con,$sql))
{
die ('Error: ' . mysqli_error($con));
}
else
{
echo "1 record added";
echo $_POST[Username];
//echo "Where is Username?";
echo $_POST[Email];
//echo "Where is Email?";
echo $_POST[Confirm];
//echo "Where is Confirm";
echo $_POST[Password];
//echo "Where is Password";
}
mysqli_close($con);
?>
</body>
UPDATE:
I added in the changes that someone had suggested in moving the checks to insert.php and now the email and confirm email check does not work. Can anyone help?
index.php
<html>
<body>
<div id="container" >
<div id="header">
<h1 id="h1">Besco's Biscuits</h1>
About
Instructions
The Creation Of The Game
Contact Us
</div>
<br /> <br /> <br />
<table align = "center">
<tr>
<td>
Welcome to <b> Besco's Biscuits </b>. Please fill out the following <br />
areas and we will begin your adventure soon. :)
</td>
</tr>
</table>
<br /> <br /> <br /> <br /> <br />
<table align = "center">
<tr>
<td>
<form action = "insert.php" method = "post"> <br />
Username: <input type="text" name="Username" id= "Username" required = "1"> <br />
Email: <input type = "text" name = "Email" id= "Email" required = "1"> <br />
Confirm: <input type = "text" name = "Confirm" id= "Confirm" required = "1"> <br />
Password: <input type = "password" name = "Password" id = "Password" required = "1"> <br />
<input type = "submit" value = "Register" id="submit_id" value = "1">
<input type = "reset" name="Reset" value="Reset Page" class = "account">
</form>
</td>
</tr>
</table>
</body>
</html>
insert.php
<html>
<body>
<?php
if($_POST['submit_id'] == 1)
{
echo "testing";
if($_POST['Email'] != $_POST['Confirm'])
{
$message = 'Your emails did not match, Please enter your emails again.';
}
}
if( $message == NULL )
{
// if there is no error, test to see if there is already an account by the player_name
$MySQLlink = new mysqli("localhost", "root", "abc123", "tower_defense");
// check connection - take out later
if ( !$MySQLlink )
{
printf( "Could not connect to MySQL server : %s", mysqli_connect_error() );
exit();
}
else
{
printf( "Connected to the MySQL server" );
echo "<br>";
}
$result = mysqli_query( $MySQLlink, "SELECT * FROM Users WHERE ( email = 'email' ) " );
if($row = mysqli_fetch_array($result))
{
$message = "There is an account with that email address already. Please choose another email account";
}
mysqli_free_result($result);
$result = mysqli_query( $MySQLlink, "SELECT * FROM Users WHERE ( Username = '$Username' ) " );
if( $row = mysqli_fetch_array($result) && $message == NULL )
{
$message = "There is an account by that player name already. Please choose another Login name";
mysqli_free_result($result);
}
else
{
//echo "next date <br>";
// create account
$Username = ($_POST['Username']);
$Password = ($_POST['Password']);
$Email = ($_POST['Email']);
$email = ($_POST['email']);
//echo "Next one<br>";
}
}
if($message != NULL)
{
echo "$message";
}
$con=mysqli_connect("localhost", "root", "abc123", "tower_defense");
//Check Connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Users (Username, Email, Confirm, Password)
VALUES
('$_POST[Username]','$_POST[Email]',' $_POST[Confirm]',' $_POST[Password]')";
if (!mysqli_query($con,$sql))
{
die ('Error: ' . mysqli_error($con));
}
else
{
echo "1 record added";
echo $_POST[Username];
//echo "Where is Username?";
echo $_POST[Email];
//echo "Where is Email?";
echo $_POST[Confirm];
//echo "Where is Confirm";
echo $_POST[Password];
//echo "Where is Password";
}
mysqli_close($con);
?>
</body>
</html>
I see two main problems here -
First, the action of your form points to itself. That means that the $_POST array submits to index.php, and your insert.php page has no access to that information. Index.php runs through the validation checks, and if everything checks out, it assigns the $_POST values to variables and quits. That's where the data dies. There is no method for getting the information over to the file insert.php. So if you manually open the file insert.php in a browser, the $_POST array will be empty, and it will simply insert blanks.
There are several ways to resolve this. The simplest, most expeditious way would be the single page solution - move the insert.php code into the index.php file inside that last else block.
else {
//echo "next date <br>";
// create account
$Username = $_POST['name'];
//etc.. code to insert data from insert.php
Another solution would be to move all the validation code to insert.php, display any form errors on that page, and make the user go back a page if validation fails. In that case, you would change the action of the form to insert.php:
<form action="insert.php" method="post">
This approach is less user-friendly, and not an ideal solution. Really a better practice is to use Javascript for form validation and PHP for form processing. That may be outside the scope of your class...
Second, this code is wide open to SQL injection. Instead of putting variables directly into your SQL statements, you need to use parameterized queries. Take a look at this SO question about how to parameterize queries with mysqli.
The mistakes that I found:
First things first your code submits the values received from the form to index.php itself so there is no question of values getting insert at the first place because the insert query is not run.
In index.php check the query to SELECT email and username. The variables do not have any value when the query is run because the values get transferred couple of lines AFTER the queries (at the lines where you have $email = $_POST['Email']). Moreover you have missed the $ sign in the query related to email.
Coming to insert.php you have missed quotes in the global variable $_POST[] in the insert query viz. $_POST['email'].
Check for these errors and let me know if it works.
I'm kinda' beginner and I've coded my own PHP login from Zero, but I still got some errors, here's the code:
<?php
include 'connection.php';
$query = " SELECT * FROM admin";
$result = mysql_query($query) or die(mysql_error());
?>
<form action="<?php echo $_SERVER['SELF_PHP']; ?>" method="post">
Username : <input type="text" name="usernameInput" value="" />
Password : <input type="password" name="passwordInput" value="" />
<input type="submit" value="Login" />
</form>
<?php
$username = $_POST['usernameInput'];
$password = $_POST['passwordInput'];
if ($username = $result['username']) {
if ($password = $result['password']){
header('Location: admin.php');
} else {
echo "PASSWORD IS INCORRECT";
}
} else {
echo "USERNAME IS INCORRECT";
}
?>
So if you can fix this or got an easier way from PHP login from please tell me. :)
A few things...
Don't use mysql functions
You need to use == to compare strings, not =
You need to actually fetch the results of your query
include 'connection.php';
$query = " SELECT * FROM admin";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result); /* add this */
?>
<form action="<?php echo $_SERVER['SELF_PHP']; ?>" method="post">
Username : <input type="text" name="usernameInput" value="" />
Password : <input type="password" name="passwordInput" value="" />
<input type="submit" value="Login" />
</form>
<?php
if(isset($_POST['usernameInput']) && isset($_POST['passwordInput'])){
$username = $_POST['usernameInput'];
$password = $_POST['passwordInput'];
}
else{
echo 'some error ...';
}
if($username == $row ['username'] && $password == $row ['password']){
header('Location: admin.php');
}
else{
echo ' username or password is wrong';
}
?>
I have to point out that you are sending the same form over and over without first checking the post. And when you send the form, you will not be able to send the header to redirect, because html is started and headers are sent already.
Mysql functions are deprecated, please use mysqli interface.
Among other several bugs like assignment = instead of is equal ==
Try it this way:
If no post exists send the form else check and if ok redirect or not ok. resend the form
<?php
if($_POST){
include 'connection.php';
$query = " SELECT * FROM admin";
$r = mysql_query($query) or die(mysql_error());
// get an associated array from query result resource.
$result = mysql_fetch_assoc($r);
$username = $_POST['usernameInput'];
$password = $_POST['passwordInput'];
if ( ($username == $result['username'])
&& ($password == $result['password'])){
header('Location: admin.php');
exit(0);
} else {
echo "PASSWORD IS INCORRECT";
}
}
?>
<form action="<?php echo $_SERVER['SELF_PHP']; ?>" method="post">
Username : <input type="text" name="usernameInput" value="" />
Password : <input type="password" name="passwordInput" value="" />
<input type="submit" value="Login" />
</form>
<?php
?>