// 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
Related
At first, I apologize for the mess of code.
I am new to PHP and I was watching a video and practicing update the password and confirmation. I was able to pass the e-mail validation(empty), however once I tried to submit password and new password along with, it kept showing that I did not fill in the password and the new password.
Could someone help me to review my code? Thank you very much.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
include ('connection.php');
$errors = array();
if (empty($_POST['email']))
{
$errors[] = 'Require your email! ';
}
else
{
$e = mysqli_real_escape_string($dbc, trim($_POST['email']));
}
if (empty($_POST['password']))
{
$errors[] = 'Require your password!';
}
else
{
$p = mysqli_real_escape_string($dbc, trim($_POST['password']));
}
if (!empty($_POST['newpass']))
{
if ($_POST['newpass'] != $_POST['conpass'])
{
$errors[] = "Your new password does not match the confirmed password!";
}
else
{
$np = mysqli_real_escape_string($dbc, trim($_POST['newpass']));
}
}
else
{
$errors[] = 'You forgot to enter your new password!';
}
if(empty($errors))
{
$q = "SELECT id FROM users WHERE (email='$e' AND password='$p')";
$r = mysqli_query($dbc, $q);
$num = mysqli_num_rows($r);
if($num == 1)
{
$row = mysqli_fetch_array($r, MYSQLI_NUM);
$q = "UPDATE users SET password='$np' WHERE id = '$row[0]'";
$r = mysqli_query($dbc, $q);
if (mysqli_affected_rows($dbc) == 1 )
{
echo "You have succesfully update your password.";
}
else
{
echo "Your password could not be changed due to a system error, please try again.";
}
mysqli_close($dbc);
}
else
{
echo "The Email and the password were in correct.";
}
}
else
{
echo "Error! The following error(s) occured: <br />";
foreach($errors as $msg)
{
echo $msg."<br />";
}
}
}
?>
<h1>Change Password</h1>
<form action="update.php" method="post">
<p>Email: <input type="text" name="email" size="20" maxlenght="30" value="<?php if(isset($_POST['email'])){echo $_POST['email'];} ?>" /></p>
<p>Current Password: <input type="password" name"password" size="20" maxlength="30" value="<?php if(isset($_POST['password'])){echo $_POST['password'];} ?>" /></p>
<p>New Password: <input type="password" name"newpass" size="20" maxlength="30" value="<?php if(isset($_POST['newpass'])){echo $_POST['newpass'];} ?>" /></p>
<p>Confirm Password: <input type="password" name"conpass" size="20" maxlength="30" value="<?php if(isset($_POST['conpass'])){echo $_POST['conpass'];} ?>" /></p>
<p><input type="submit" name="submit" value="Change Password" /></p>
</form>
You have syntax errors in your HTML code.
You missed = signs at these lines:
<input type="password" name"password" ...
should be <input type="password" name = "password"
<input type="password" name"newpass" ...
should be <input type="password" name = "password"
<input type="password" name"conpass" ...
should be <input type="password" name = "conpass"
The name tag is important for GET and POST methods. Thats what allows data to be sent from the input fields to the server.
OK, here is updated version of your code:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
include ('connection.php');
$errors = array();
$email=trim($_POST['email']);
$password=trim($_POST['password']);
$newpass=trim($_POST['newpass']);
$conpass=trim($_POST['conpass']);
if (empty($email)) {
$errors[] = 'Require your email! ';
} else {
$e = mysqli_real_escape_string($dbc, $email);
}
if (empty($password)) {
$errors[] = 'Require your password!';
} else {
$p = mysqli_real_escape_string($dbc, $password);
}
if (!empty($newpass)) {
if ($newpass != $conpass){
$errors[] = "Your new password does not match the confirmed password!";
} else {
$np = mysqli_real_escape_string($dbc, $newpass));
}
} else {
$errors[] = 'You forgot to enter your new password!';
}
if(empty($errors)){
$q = "SELECT `id` FROM `users` WHERE (`email` LIKE '$e' AND `password` LIKE '$p') LIMIT 0, 1";
$r = mysqli_query($dbc, $q);
$num = mysqli_num_rows($r);
if($num == 1){
$row = mysqli_fetch_array($r, MYSQLI_NUM);
$q = "UPDATE `users` SET `password` LIKE '$np' WHERE `id = '$row[0]'";
$r = mysqli_query($dbc, $q);
if (mysqli_affected_rows($dbc) == 1 ){
echo "You have succesfully update your password.";
} else {
echo "Your password could not be changed due to a system error, please try again.";
}
mysqli_close($dbc);
} else {
echo "The Email and the password were in correct.";
}
} else {
echo "Error! The following error(s) occured: <br />";
foreach($errors as $msg){
echo $msg."<br />";
}
}
}
First before empty() check you need to trim() POST's, Also in MySQL query strings you need to search with LIKE for password and email, not = becouse that is string not integer.
Also:
<p>Email: <input type="text" name="email" size="20" maxlenght="30" value="<?php if(isset($_POST['email'])){echo $_POST['email'];} ?>" /></p>
<p>Current Password: <input type="password" name="password" size="20" maxlength="30" value="<?php if(isset($_POST['password'])){echo $_POST['password'];} ?>" /></p>
<p>New Password: <input type="password" name="newpass" size="20" maxlength="30" value="<?php if(isset($_POST['newpass'])){echo $_POST['newpass'];} ?>" /></p>
<p>Confirm Password: <input type="password" name="conpass" size="20" maxlength="30" value="<?php if(isset($_POST['conpass'])){echo $_POST['conpass'];} ?>" /></p>
<p><input type="submit" name="submit" value="Change Password" /></p>
You forgot to put = after name attributes.
I've been trying to troubleshoot a problem I have but I've had no luck so far.
I have a profile page that echoes the user's first and last name. This function works when users first register. The problem is, however, that when the user logs out (ending session) and logs back in and goes back to his/her profile page, the first and last names do not show, leaving instead blanks.
To better clarify consider the pathways:
1.User registers -> profile displays first and last name
2.User logs in -> profile does not display first and last name
Here are the codes pertaining to this issue (I already have session_start() at the top of each page I have; also, my variables, reg form and login form are under one php enclosure):
Variables:
<?php
error_reporting(E_ALL ^ E_NOTICE);
$reg = $_POST['reg'];
//initializing registration variables to prevent errors
$fn = ""; //first name
$ln = ""; //last name
$em = ""; //email
$em2 = ""; //email 2
$pass = ""; //password
$bday = ""; //birthday
$sud = ""; //sign up date
$em_check =""; //check if email exists
//registration variables + form
$fn = mysqli_real_escape_string($con, $_POST['first_name']);
$ln = mysqli_real_escape_string($con, $_POST['last_name']);
$em = mysqli_real_escape_string($con, $_POST['email']);
$em2 = mysqli_real_escape_string($con, $_POST['email2']);
$pass = mysqli_real_escape_string($con, $_POST['password']);
$bday = date("Y");
$sud = date("Y-m-d H:i:s"); // Year - Month - Day
Registration Form:
if(isset($_POST['reg'])) {
if($em==$em2) {
//check if email already exists
$emSQLI = "SELECT email FROM `users` WHERE email='$em'";
$em_check = mysqli_query($con, $emSQLI); //checks whether both entered emails are identical
$check = mysqli_num_rows($em_check); //count the amount of rows where email = $em
if ($check == 0) {
//check if all fields have been filled
if($fn && $ln && $em && $em2 && $pass && $bday) {
//check the maximum length of relevant fields
if(strlen($fn)>90||strlen($ln)>90) {
echo "Maximum limit for first/last names is 90 characters.";
}
else{
if (strlen($pass)<6||strlen($pass)>99) {
echo "Password must be between 6 and 99 characters long.";
}
else {
$pass = md5($pass);
$regSQLI = "INSERT INTO users (id, email, birth_date, first_name, last_name, password, sign_up_date, activated) VALUES ('','$em','$bday','$fn','$ln','$pass','$sud','0')";
$regQuery = mysqli_query($con, $regSQLI);
//variables that will be passed over from the register fields to forthcoming sessions
$_SESSION["email_login"] = $em;
$_SESSION["first_name"] = $fn;
$_SESSION["last_name"] = $ln;
}
}
header("location: profile.php");
exit();
}
else {
echo '<div id="regerrormsg">Please fill in all required fields. </div>';
}
}
else {
echo '<div id="regerrormsg"> Email is already registered. </div>';
}
}
else {
echo '<div id="regerrormsg">Entered emails do not match. </div>';
}
}
Log In Form:
if(isset($_POST['email_login']) && isset($_POST['pass_login'])) {
$email_login = mysqli_real_escape_string($con, $_POST['email_login']);
$pass_login = mysqli_real_escape_string($con, $_POST['pass_login']);
$pass_login = md5($pass_login);
$logquery = "SELECT id FROM users WHERE email='$email_login' AND password='$pass_login' LIMIT 1";
$sqli = mysqli_query($con, $logquery);
$userCount = mysqli_num_rows($sqli); // Count number of rows returned
// checks the database for respective items
if ($userCount == 1) { //if the search finds a matching record of the login input form
while( $row = mysqli_fetch_assoc($sqli)) { // use fetch_assoc
$id = $row["id"];
}
$_SESSION["email_login"] = $email_login;
$_SESSION["first_name"] = $fn;
$_SESSION["last_name"] = $ln;
header("location: home.php");
exit();
}
else {
echo '<div id="regerrormsg">Login information is invalid. </div>';
}
}
And finally, the profile page that displays the names:
<?php
session_start();
include ( "./inc/connect.inc.php");
if(!isset($_SESSION["email_login"])) {
header("location: index.php");
exit();
}
else {
}
?>
<?php
echo "Delighted to have you here, " .$_SESSION["first_name"]." ".$_SESSION["last_name"].".";
?>
I am stuck and would like help in troubleshooting this, thank you!
EDIT: Here are the html codes:
Login Form:
<form action="index.php" method="POST">
<input type="email" name="email_login" size="60" placeholder="Email" /><br /><br /><br />
<input type="password" name="pass_login" size="60" placeholder="Password" /><br /><br /><br />
<input type="submit" name="login" id="login" value="LOG IN">
</form>
Register Form:
<form action="index.php" method="POST">
<input type="text" name="first_name" size="15" placeholder="First name" /><br /><br /><br />
<input type="text" name="last_name" size="15" placeholder="Last name" /><br /><br /><br />
<input type="email" name="email" size="15" placeholder="Email" /><br /><br /><br />
<input type="email" name="email2" size="25" placeholder="Re-enter email" /><br /><br /><br />
<input type="password" name="password" size="15" placeholder="New password" /><br /><br /><br />
<p5>Birthyear</p5><br />
<div id="date1" class="datefield">
<input id="birth_year" type="tel" name="birth_year" maxlength="4" placeholder="YYYY" />
</div>
<input type="submit" name="reg" value="Sign Up"><br />
</form>
In your Log form, replace this
$logquery = "SELECT id FROM users WHERE email='$email_login' AND password='$pass_login' LIMIT 1";
$sqli = mysqli_query($con, $logquery);
$userCount = mysqli_num_rows($sqli); // Count number of rows returned
// checks the database for respective items
if ($userCount == 1) { //if the search finds a matching record of the login input form
while( $row = mysqli_fetch_assoc($sqli)) { // use fetch_assoc
$id = $row["id"];
}
$_SESSION["email_login"] = $email_login;
$_SESSION["first_name"] = $fn; // -> $fn not defined
$_SESSION["last_name"] = $ln; // -> $ln not defined
header("location: home.php");
exit();
}
else {
echo '<div id="regerrormsg">Login information is invalid. </div>';
}
By this
$logquery = "SELECT * FROM users WHERE email='$email_login' AND password='$pass_login' LIMIT 1";
$sqli = mysqli_query($con, $logquery);
$userCount = mysqli_num_rows($sqli); // Count number of rows returned
// checks the database for respective items
if ($userCount == 1) { //if the search finds a matching record of the login input form
while( $row = mysqli_fetch_assoc($sqli)) { // use fetch_assoc
$id = $row["id"];
$_SESSION["email_login"] = $row["email"];
$_SESSION["first_name"] = $row["first_name"]; // -> retrieve the data from the result of the query
$_SESSION["last_name"] = $row["last_name"];
}
// EDIT: i moved the $_SESSION part above, my bad !
header("location: home.php");
exit();
}
else {
echo '<div id="regerrormsg">Login information is invalid. </div>';
}
Hope it will help.
I'm trying to insert data into the 'riders' table in the 'poo12104368' database using a form. Currently I am having problems with my 'if' statements because they are not working as they should be. For example, if a user was to only type in a last name and an email address, it would let them create an account. When the user does create an account by entering their correct details into the feilds it should take them to 'newaccount.php'. Can anybody help? Thanks
Code:
$firstnameErr = $lastnameErr = $suemailErr = "";
$firstname = $lastname = $suemail = "";
if(isset($_POST['submit2'])){
if(empty($_POST["firstname"])||(empty($_POST["lastname"]))||(empty($_POST["suemail"]))){
echo "Something is wrong";
if($_POST['firstname'] == null){
$firstnameErr = "First Name is required";
}else{
$firstname =($_POST["firstname"]);
}
if($_POST['lastname'] == null){
$lastnameErr = "Last Name is required";
}else{
$lastname = ($_POST["lastname"]);
}
if($_POST['suemail'] == null){
$suemailErr = "Email is required";
}else{
$suemail = ($_POST["suemail"]);
}
if($_POST['firstname'] == null){
echo "<b>Please enter a first name</b>";
}
else if($_POST['lastname'] == null){
echo "<b><p>Please enter a last name</p></b>";
}
else if($_POST['suemail'] == null){
echo "<b><p>Please enter an email</p></b>";
}
$dblink = mysql_connect("localhost", "root", "" )
or die (mysql_error());
mysql_select_db("poo12104368");
// Query the database to see if the email that the user has entered is already in use
$rs2 = mysql_query("SELECT * FROM riders WHERE Email = '".$_POST['suemail']."'");
if($row = mysql_fetch_assoc($rs2)){
$dbEmail = $row['Email'];
if($row['Email'] == $_POST['suemail']){
echo "<p><b>Email already used. Please use another</b></p>";
}
}
else{
// Insert query to insert the data into the riders table if their data meets the required inputs
$sql = "
INSERT INTO riders (FirstName, LastName, Email) VALUES('".$_POST['firstname']."','".$_POST['lastname']."','".$_POST['suemail']."')";
mysql_query($sql);
// The web page that the user will be taken to
header('Location:http://localhost/newaccount.php');
}
}
}
?>
<h2><p> Sign Up </p></h2>
<p><span class="error">* required field.</span></p>
<!-- Form that the users enters their data in -->
<form name = "suform" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p>First Name:<input type="text" name="firstname" style="width:20%"/>
<span class="error">*<?php echo $firstnameErr;?></span></p></br>
<p>Last Name:<input type="text" name="lastname" style="width:20%"/>
<span class="error">*<?php echo $lastnameErr;?></span></p></br>
<p>Email Address:<input type="text" name="suemail" style="width:20%"/></p>
<span class="error">*<?php echo $suemailErr;?></span></br>
<p><br><input type="submit" name="submit2" value="Submit"/></br></p>
<h2>Our Links</h2>
<!-- Links to the various mediums for Bewdley Motorcycle Club -->
<p>YouTube:BewdleyMCCOffcial<p>
<p>Website:www.bewdleymotorcycleclub.co.uk</p>
Try this it will work :
Use flag to handle the validation errors in the form use this $error as a flag.
Code :
$firstnameErr = $lastnameErr = $suemailErr = "";
$firstname = $lastname = $suemail = "";
if(isset($_POST['submit2'])){
$error = 0;
if(empty($_POST["firstname"])||(empty($_POST["lastname"]))||(empty($_POST["suemail"]))){
$msg = "something going wrong";
$error = 1;
}
if($_POST['firstname'] == null){
$firstnameErr = "First Name is required";
$error = 1;
}else{
$firstname =($_POST["firstname"]);
}
if($_POST['lastname'] == null){
$lastnameErr = "Last Name is required";
$error = 1;
}else{
$lastname = ($_POST["lastname"]);
}
if($_POST['suemail'] == null){
$suemailErr = "Email is required";
$error = 1;
}else{
$suemail = ($_POST["suemail"]);
}
if($_POST['firstname'] == null){
$msg = "Please enter a first name";
$error = 1;
}
else if($_POST['lastname'] == null){
$msg = "Please enter a last name";
$error = 1;
}
else if($_POST['suemail'] == null){
$msg = "Please enter an email";
$error = 1;
}
if($error == '0')
{
$dblink = mysql_connect("localhost", "root" , "")
or die (mysql_error());
mysql_select_db("poo12104368");
// Query the database to see if the email that the user has entered is already in use
$rs2 = mysql_query("SELECT * FROM riders WHERE Email = '".$_POST['suemail']."'");
if($row = mysql_fetch_assoc($rs2)){
$dbEmail = $row['Email'];
if($row['Email'] == $_POST['suemail']){
echo "<p><b>Email already used. Please use another</b></p>";
}
}
else{
// Insert query to insert the data into the riders table if their data meets the required standards
$sql = "
INSERT INTO riders (FirstName, LastName, Email) VALUES('".$_POST['firstname']."','".$_POST['lastname']."','".$_POST['suemail']."')";
mysql_query($sql);
// The web page that the user will be taken to
header('Location:http://localhost/newaccount.php');
}
}
else
{
echo $msg;
}
?>
<h2><p> Sign Up </p></h2>
<p><span class="error">* required field.</span></p>
<!-- Form that the users enters their data in -->
<form name = "suform" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p>First Name:<input type="text" name="firstname" style="width:20%"/>
<span class="error">*<?php echo $firstnameErr;?></span></p></br>
<p>Last Name:<input type="text" name="lastname" style="width:20%"/>
<span class="error">*<?php echo $lastnameErr;?></span></p></br>
<p>Email Address:<input type="text" name="suemail" style="width:20%"/></p>
<span class="error">*<?php echo $suemailErr;?></span></br>
<p><br><input type="submit" name="submit2" value="Submit"/></br></p>
<h2>Our Links</h2>
<!-- Links to the various mediums for Bewdley Motorcycle Club -->
<p>YouTube:BewdleyMCCOffcial<p>
<p>Website:www.bewdleymotorcycleclub.co.uk</p>
I hope it will work for you.
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
I'm having a lot of trouble with the $_SESSION variable. I'm trying to create a way for users to log in and out. I can log a user in but i don't seem to be able to maintain the session when i switch page. When the user correctly logs in they are taken to profile.php. But if i return to index.php the following error is printed:
Notice: Undefined index: login in /Applications/MAMP/htdocs/www/Shared sites/userlogreg/index.php on line 3
I'm quite new to this but from looking on SO and elsewhere i can't seem to figure it out. Any help would be appreciated.
index.php
<?php
session_start();
if ($_SESSION['login'] == 1) {
echo "<h1>Logged in!</h1>";
} else {
echo "<h1>Not logged in</h1><br/>";
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Index page</title>
</head>
<body>
<h2>Login</h2>
<form action="login.php" method="POST">
<div>
<label for="emailSignIn">Email:</label>
<input type="email" name="email" placeholder="Email" required="required" />
</div>
<div>
<label for="passwordSignIn">Password:</label>
<input type="password" name="password" placeholder="Password" required="required" />
</div>
<input type="submit" name="submit" value="Sign in" />
</form>
<h2>Register</h2>
<form action="register.php" method="POST">
<div>
<label for="firstnameRegister">First name:</label>
<input type="text" name="firstname" placeholder="First name" required="required" />
</div>
<div>
<label for="lastnameRegister">Last name:</label>
<input type="text" name="lastname" placeholder="Last name" required="required" />
</div>
<div>
<label for="emailRegister">Email:</label>
<input type="email" name="email" placeholder="Email" required="required" />
</div>
<div>
<label for="passwordRegister">Password:</label>
<input type="password" name="password" placeholder="Password" required="required">
</div>
<input type="submit" name="submit" value="Create account" />
</form>
</body>
</html>
login.php
<?php
$email = sanitize_input($_POST['email']); //echo "Sanitized email: ".$email; echo "<br/>";
$password = $_POST['password']; //echo "Inputted password: ".$password; echo "<br/>";
if ((!isset($email)) || (!isset($password))) {
// VISITOR NEEDS TO ENTER AN EMAIL AND PASSWORD
//echo "Data not provided";
} else {
// CONNECT TO MYSQL
$mysql = mysqli_connect("localhost", "root", "root");
if(!$mysql) {
//echo "Cannot connect to PHPMyAdmin.";
exit;
} else {
}
}
// SELECT THE APPROPRIATE DATABASE
$selected = mysqli_select_db($mysql, "languageapp");
if(!$selected) {
//echo "Cannot select database.";
exit;
} else {
}
// GET THE USER'S UNIQUE SALT FROM THE DATABASE
$unique_salt = mysqli_query($mysql, "select uniqueSalt from user where email = '".$email."'");
$row = mysqli_fetch_array($unique_salt);
//echo "Salt: ".$row['uniqueSalt']; echo "<br/>";
// HASH THE PASSWORD
$iterations = 10;
$hashed_password = crypt($password,$row['uniqueSalt']);
for ($i = 0; $i < $iterations; ++$i)
{
$hashed_password = crypt($hashed_password . $password,$row['uniqueSalt']);
}
//echo "Password entered by user: ".$hashed_password; echo "<br/>";
$user_db_password = mysqli_query($mysql, "select password from user where email = '".$email."'");
$row = mysqli_fetch_array($user_db_password);
//echo "User's password: ".$row['password']; echo "<br/>";
// query the database to see if there is a record which matches
$query = "select count(*) from user where email = '".$email."' and password = '".$hashed_password."'";
$result = mysqli_query($mysql, $query);
if(!$result) {
//echo "Cannot run query.";
exit;
}
$row = mysqli_fetch_row($result);
$count = $row[0];
if ($count > 0) {
session_start();
$_SESSION['login'] = 1;
$_SESSION['email'] = $email;
$_SESSION['errors'] = "";
header("location:profile.php");
//echo "<h1>Login successful!</h1>";
//echo "<p>Welcome.</p>";
//echo "<p>This page is only visible when the correct details are provided.</p>";
} else {
session_start();
$_SESSION['login'] = '';
header("location:index.php");
//echo "<h1>Login unsuccessful!</h1>";
//echo "<p>The email and password combination entered was not recognized</p>";
}
// CLEAN THE INPUT
function sanitize_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Change this line:
if ($_SESSION['login'] == 1) {
..to this:
if (isset($_SESSION['login']) && $_SESSION['login'] == 1) {
That way, you check if 'login' is set before you access it.