I want to delete data from database if the same exists in database, but my coding is not working. if user input data is not matching then a error warning should be display.
HTML
<form action="" method="POST">
<input type="number" name="student_id_delete" placeholder="Enter Student ID"/>
<input type="submit" name="sub_delete" value="Delete"/>
</form>
PHP
define('HOST','localhost');
define('USER','root');
define('PASSWORD_HOST','');
define('DATABASE','ubhs');
if(defined('HOST') && defined('USER') && defined('PASSWORD_HOST') && defined('DATABASE')){
$conn = mysqli_connect(HOST, USER, PASSWORD_HOST, DATABASE);
}else{
die(connection_failed.mysqli_connection_error());
}
$userinput = true;
$student_id_delete = $_POST['student_id_delete'];
if(isset($_POST['sub_delete'])){
if(empty($student_id_delete)){
$userErr1 = "Please enter student ID to be deleted";
$userinput = false;
}
$sql = "SELECT FROM student_info WHERE id=$student_id_delete";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result)<0){
echo "student could not be found in database";
$userinput = false;
}
if($userinput==true){
$sql = "DELETE FROM student_info WHERE id=$student_id_delete";
if(mysqli_query($conn,$sql)){
echo "Success";
}else{
echo "Couldn't deleted";
}
}
}
Try below snippet :
HTML code :
<form action="" method="POST">
<input type="number" name="student_id_delete" placeholder="Enter Student ID"/>
<input type="submit" name="sub_delete" value="Delete"/>
</form>
PHP code :
<?php
define('HOST','localhost');
define('USER','root');
define('PASSWORD_HOST','');
define('DATABASE','ubhs');
if(defined('HOST') && defined('USER') && defined('PASSWORD_HOST') && defined('DATABASE'))
{
$conn = mysqli_connect(HOST, USER, PASSWORD_HOST, DATABASE);
}
else
{
die(connection_failed.mysqli_connection_error());
}
$userinput = true;
$student_id_delete = $_POST['student_id_delete'];
if(isset($_POST['sub_delete']))
{
if(empty($student_id_delete))
{
$userErr1 = "Please enter student ID to be deleted";
$userinput = false;
}
if($userinput==true)
{
$sql = "DELETE FROM student_info WHERE id=".mysqli_real_escape_string($student_id_delete); // sql injection prevention.
mysqli_query($conn,$sql);
echo "Records deleted: ".mysqli_affected_rows($conn);
}
}
?>
OUTPUT :
Records deleted: 1
Records deleted: 0
Related
I am new to PHP coding. I have created two forms. One is for signing up and the other for logging in. Unfortunately both fail to work due to some issues in the queries. I also searched and went through similar posts on this site but none solved my problem. I want to verify whether a user with the same id exists in the database "Users.db" at the time of signing up if any user enters the same id he should be notified to enter a valid id.
When I run my "sign in.php" code, it displays the following message on the screen without even waiting for the user to press the submit button/ sign up button.. "Number of rows found: 1 .This id is not available. Please enter a valid id." This message gets displayed even if the user enters a unique id that doesnt exist in the database before. Nothing gets stored in my database even if the id is unique by pressing the sign up button.
Secondly while logging in, the id and password entered by the user must be verified and matched with those stored in the database. He should be directed to the "index.html" page after successfully login in and only if he has signed up before. He should also be able to view his search history that is stored in "Search" table in the same database. This table contains two columns. One for the User id and the other for saving his search results.
The Search table looks like:
Id | History
nl23 Grand Hayat Hotel
Pearls Residencia Hotels
I am getting this error after running my code for login form "Unable to prepare statement: 1, near "AND": syntax error in D:\log in.php on line 54".
My log in form code is below:
log in.php
<body>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
label{display:inline-block;width:100px;margin-bottom:10px;}
</style>
</head>
<body>
<h2>Log in page</h2>
<form method="post" action="">
Id: <input type="text" name="Id">
<br><br>
Password: <input type="text" name="Password">
<br><br>
<input type="submit" name="submit" value="Log In" >
</form>
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('Users Data.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
}
$id=null;
$pass=null;
$id_exists=null;
if (isset($_POST['uid'])) {
$id = $_POST['uid'];
}
if (isset($_POST['passid'])) {
$pass = $_POST['passid'];
}
$sql= " SELECT * FROM Users WHERE ID = '" .$id. "' AND PASSWORD = '" .$pass. "';";
$ret = $db->query($sql);
$rows = count($sql);
if ($rows > 0)
{
$id_exists = true;
echo "You entered a valid id and password. ";
$sql= "SELECT History FROM Search WHERE Id= " .$id. ";";
$ret = $db->query($sql);
//header("location:index.html");
}
else
{
echo "Please enter a valid id and password. ";
}
?>
</body>
</html>
My sign in form is below:
sign in.php
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
label{display:inline-block;width:100px;margin-bottom:10px;}
</style>
</head>
<body>
<h2>Sign in page</h2>
<form method="post" action="">
Id: <input type="text" name="Id">
<br><br>
Password: <input type="text" name="Password">
<br><br>
Email: <input type="text" name="Email">
<input type="submit" name="submit" value="Sign Up" >
</form>
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('Users Data.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
}
$id=null;
$password=null;
$email=null;
$id_exists=false;
$sql=null;
$result=null;
$rows=null;
$ret=null;
if (isset($_POST['Id'])) {
$id = $_POST['Id'];
}
if (isset($_POST['Password'])) {
$password = $_POST['Password'];
}
if (isset($_POST['Email'])) {
$email = $_POST['Email'];
}
$result= "SELECT * FROM Users WHERE ID = " .$id. ";";
// $ret = $db->query($result);
//$ret = $db->exec($sql);
echo "<p> The result query is ".$result ."</p>";
$rows = count($result);
echo "<p> Number of rows found: ".$rows ."</p>";
if ($rows > 0)
{
$id_exists = true;
echo "This id is not available. Please enter a valid id. ";
}
else
{
$sql= "INSERT INTO Users (ID,PASSWORD, EMAIL)
VALUES ('$id','$password','$email');" ;
$ret = $db->query($sql);
//$ret = $db->exec($sql);
// header("location:index.html");
}
if(!$ret){
echo $db->lastErrorMsg();
} else {
}
$db->close();
?>
</body>
</html>
Please guide me as i am stuck in both these codes.
What you are missing is checking if $_POST is set or is not empty. Only then you want to process user input. One more thing is that you should wrap $pass in quotes as it is a string and will be interpreted as column name if not surrounded with quotes.
Here's code:
log in.php
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
label{display:inline-block;width:100px;margin-bottom:10px;}
</style>
</head>
<body>
<h2>Log in page</h2>
<form method="post" action="">
Id: <input type="text" name="Id">
<br><br>
Password: <input type="text" name="Password">
<br><br>
<input type="submit" name="submit" value="Log In" >
</form>
<?php
if(!empty($_POST)) {
class MyDB extends SQLite3
{
function __construct()
{
$this->open('Users Data.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
}
$id=null;
$pass=null;
$id_exists=null;
if (isset($_POST['Id'])) {
$id = $_POST['Id'];
}
if (isset($_POST['Password'])) {
$pass = $_POST['Password'];
}
$sql= " SELECT * FROM Users WHERE ID = '" .$id. "' AND PASSWORD = '" .$pass. "';";
$ret = $db->query($sql);
$rows = count($sql);
if ($rows > 0)
{
$id_exists = true;
echo "You entered a valid id and password. ";
$sql= "SELECT History FROM Search WHERE Id= " .$id. ";";
$ret = $db->query($sql);
//header("location:index.html");
}
else
{
echo "Please enter a valid id and password. ";
}
}
?>
</body>
</html>
sign in.php:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
label{display:inline-block;width:100px;margin-bottom:10px;}
</style>
</head>
<body>
<h2>Sign in page</h2>
<form method="post" action="">
Id: <input type="text" name="Id">
<br><br>
Password: <input type="text" name="Password">
<br><br>
Email: <input type="text" name="Email">
<input type="submit" name="submit" value="Sign Up" >
</form>
<?php
if(!empty($_POST)) {
class MyDB extends SQLite3
{
function __construct()
{
$this->open('Users Data.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
}
$id=null;
$password=null;
$email=null;
$id_exists=false;
$sql=null;
$result=null;
$rows=null;
$ret=null;
if (isset($_POST['Id'])) {
$id = $_POST['Id'];
}
if (isset($_POST['Password'])) {
$password = $_POST['Password'];
}
if (isset($_POST['Email'])) {
$email = $_POST['Email'];
}
$result= "SELECT * FROM Users WHERE ID = " .$id. ";";
echo "<p> The result query is ".$result ."</p>";
$rows = count($result);
echo "<p> Number of rows found: ".$rows ."</p>";
if ($rows > 0)
{
$id_exists = true;
echo "This id is not available. Please enter a valid id. ";
}
else
{
$sql= "INSERT INTO Users (ID,PASSWORD, EMAIL)
VALUES ('$id','$password','$email');" ;
$ret = $db->query($sql);
//$ret = $db->exec($sql);
// header("location:index.html");
}
if(!$ret){
echo $db->lastErrorMsg();
} else {
}
$db->close();
}
?>
</body>
</html>
I'm trying to figure out how to upload a file into the database where that form contains multiple textfields. I uploaded a BLOB field into the database. So as I try to search the field using the ID number, it will retrieve me the values associated with it. Which works fine, so I added the function of being able to upload a file into that specific id number. I get all sorts of errors and I would like to have an assistance with it. Anyone care to help out? Here are the codes:
<?php
$host = "localhost";
$user = "root";
$password ="";
$database = "ntmadb";
$id = "";
$firstname = "";
$lastname = "";
$username = "";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// connect to mysql database
try{
$connect = mysqli_connect($host, $user, $password, $database);
} catch (mysqli_sql_exception $ex) {
echo 'Error';
}
// get values from the form
function getPosts()
{
$posts = array();
$posts[0] = $_POST['id'];
$posts[1] = $_POST['firstname'];
$posts[2] = $_POST['lastname'];
$posts[3] = $_POST['username'];
return $posts;
}
// Search
if(isset($_POST['search']))
{
$data = getPosts();
$search_Query = "SELECT * FROM members WHERE id = $data[0]";
$search_Result = mysqli_query($connect, $search_Query);
if($search_Result)
{
if(mysqli_num_rows($search_Result))
{
while($row = mysqli_fetch_array($search_Result))
{
$id = $row['id'];
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$username = $row['username'];
}
}else{
echo 'No Data For This Id';
}
}else{
echo 'Result Error';
}
}
// Edit
if(isset($_POST['update']))
{
$data = getPosts();
$update_Query = "UPDATE `members` SET `firstname`='$data[1]',`lastname`='$data[2]',`username`='$data[3]' WHERE `id` = $data[0]";
try{
$update_Result = mysqli_query($connect, $update_Query);
if($update_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Updated';
}else{
echo 'Data Not Updated';
}
}
} catch (Exception $ex) {
echo 'Error Update '.$ex->getMessage();
}
}
<!--UPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOAD -->
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', '', 'ntmadb');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
// Create the SQL query
$query = "
INSERT INTO `members` (
`data`
)
VALUES (
'{$data}' NOW()
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
?>
and here is the html file:
<!DOCTYPE Html>
<html>
<head>
<title>PHP INSERT UPDATE DELETE SEARCH</title>
</head>
<body>
<form action="index4.php" method="post" enctype="multipart/form-data" >
<input type="number" name="id" placeholder="Id" value="<?php echo $id;?>"><br><br>
<input type="text" name="firstname" placeholder="First Name" value="<?php echo $firstname;?>"><br><br>
<input type="text" name="lastname" placeholder="Last Name" value="<?php echo $lastname;?>"><br><br>
<input type="text" name="username" placeholder="User Name" value="<?php echo $username;?>"><br><br>
<div>
<p>
<!-- Input For Edit Values -->
<input type="submit" name="update" value="Update">
<!-- Input For Find Values With The given ID -->
<input type="submit" name="search" value="Find">
</p>
<p>
<input type="file" name="uploaded_file">
<br>
<input type="submit" value="Upload file">
</p>
</div>
</form>
</body>
</html>
Thanks to anyone who can provide me with help. :)
It's a student database system where I can add student data, edit student data, delete student data, and search student data from registration number.
Here is where I'm getting a problem. All is ok but phone number will not be saved in mysql database. All other option are edit and insert in database.
I did not get any error when I edit any information or add new data.
When I submit phone number direct from phpmyadmin then from my index page when I put registration number then get all information of student without phone number.
Here is index.php code:
<?php
$host = "localhost";
$user = "root";
$password ="root";
$database = "college";
$student_reg = "";
$student_name = "";
$father_name = "";
$phone_number = "";
$student_address = "";
$student_course = "";
$student_certificatenumber = "";
$student_email = "";
$student_city = "";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// connect to mysql database
try{
$connect = mysqli_connect($host, $user, $password, $database);
} catch (mysqli_sql_exception $ex) {
echo 'Error';
}
// get values from the form
function getPosts()
{
$posts = array();
$posts[7] = $_POST['student_reg'];
$posts[1] = $_POST['student_name'];
$posts[2] = $_POST['father_name'];
$posts[3] = $_POST['phone_number'];
$posts[4] = $_POST['student_address'];
$posts[5] = $_POST['student_course'];
$posts[6] = $_POST['student_certificatenumber'];
$posts[8] = $_POST['student_email'];
$posts[9] = $_POST['student_city'];
return $posts;
}
// Search
if(isset($_POST['search']))
{
$data = getPosts();
$search_Query = "SELECT * FROM students WHERE student_reg = $data[7]";
$search_Result = mysqli_query($connect, $search_Query);
if($search_Result)
{
if(mysqli_num_rows($search_Result))
{
while($row = mysqli_fetch_array($search_Result))
{
$student_reg = $row['student_reg'];
$student_name = $row['student_name'];
$father_name = $row['father_name'];
$phone_number = $row['phone_number'];
$student_address = $row['student_address'];
$student_course = $row['student_course'];
$student_certificatenumber = $row['student_certificatenumber'];
$student_email = $row['student_email'];
$student_city = $row['student_city'];
}
}else{
echo 'No Data For This Id';
}
}else{
echo 'Result Error';
}
}
// Insert
if(isset($_POST['insert']))
{
$data = getPosts();
$insert_Query = "INSERT INTO `students`(`student_reg`, `student_name`, `father_name`, `phone_number`,
`student_address`, `student_course`, `student_certificatenumber`, `student_email`, `student_city`) VALUES ('$data
[7]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[8]','$data[9]')";
try{
$insert_Result = mysqli_query($connect, $insert_Query);
if($insert_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Inserted';
}else{
echo 'Data Not Inserted';
}
}
} catch (Exception $ex) {
echo 'Error Insert '.$ex->getMessage();
}
}
// Delete
if(isset($_POST['delete']))
{
$data = getPosts();
$delete_Query = "DELETE FROM `students` WHERE `student_reg` = $data[7]";
try{
$delete_Result = mysqli_query($connect, $delete_Query);
if($delete_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Deleted';
}else{
echo 'Data Not Deleted';
}
}
} catch (Exception $ex) {
echo 'Error Delete '.$ex->getMessage();
}
}
// Edit
if(isset($_POST['update']))
{
$data = getPosts();
$update_Query = "UPDATE `students` SET `student_reg`='$data[7]',`student_name`='$data[1]',`father_name`='$data
[2]',`phone_number`='$data[3]',`student_address`='$data[4]',`student_course`='$data
[5]',`student_certificatenumber`='$data[6]',`student_email`='$data[8]',`student_city`='$data[9]' WHERE
`student_reg` = $data[7]";
try{
$update_Result = mysqli_query($connect, $update_Query);
if($update_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Updated';
}else{
echo 'Data Not Updated';
}
}
} catch (Exception $ex) {
echo 'Error Update '.$ex->getMessage();
}
}
?>
<!DOCTYPE Html>
<html>
<head>
<title>PHP INSERT UPDATE DELETE SEARCH</title>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="student_reg" placeholder="Student Registration Code" value="<?php echo
$student_reg;?>"><br><br>
<input type="text" name="student_name" placeholder="Name" value="<?php echo $student_name;?>"><br><br>
<input type="text" name="father_name" placeholder="Student Father Name" value="<?php echo
$father_name;?>"><br><br>
<input type="text" name="Phone_number" placeholder="Phone Mobile Number" value="<?php echo
$Phone_number;?>"><br><br>
<input type="text" name="student_address" placeholder="Address" value="<?php echo $student_address;?
>"><br><br>
<input type="text" name="student_course" placeholder="Course" value="<?php echo $student_course;?
>"><br><br>
<input type="text" name="student_certificatenumber" placeholder="Certificate Number" value="<?php echo
$student_certificatenumber;?>"><br><br>
<input type="text" name="student_email" placeholder="EMail" value="<?php echo $student_email;?
>"><br><br>
<input type="text" name="student_city" placeholder="City" value="<?php echo $student_city;?>"><br><br>
<div>
<!-- Input For Add Values To Database-->
<input type="submit" name="insert" value="Add">
<!-- Input For Edit Values -->
<input type="submit" name="update" value="Update">
<!-- Input For Clear Values -->
<input type="submit" name="delete" value="Delete">
<!-- Input For Find Values With The given ID -->
<input type="submit" name="search" value="Find">
</div>
</form>
</body>
</html>
check datatype of your phonenumber column in mysql database make it of string type...it may solve your problem
$posts[3] = $_POST['phone_number']
is not the same as
<input type="text" name="Phone_number"
Phone_number is not = to phone_number. PHP is case sensitive.
// 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
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