It tried updating to database but it is not working - php

<?php
include('config/db_connect.php');
$title = $email = $ingredients ='';
$errors = array('email'=>'', 'title'=>'', 'ingredient'=>'');
if(isset($_POST['update'])){
//Check email
if(empty($_POST['email'])){
$errors['email'] ='an email is required <br />';
} else{
$email = $_POST['email'];
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors['email'] = 'Email must be a valid email address';
}
}
//Check title
if(empty($_POST['title'])){
$errors['title'] ='a title is required <br />';
} else{
$title = $_POST['title'];
if(!preg_match('/^[a-zA-Z\s]+$/', $title)){
$errors['title'] = 'Title must be letters and spaces only';
}
}
//Check ingredients
if(empty($_POST['ingredients'])){
$errors['ingredient'] = 'at least one ingredent is required <br />';
} else{
$ingredients = $_POST['ingredients'];
if(!preg_match('/^([a-zA-Z\s]+)(,\s*[a-zA-Z\s]*)*$/', $ingredients)){
$errors['ingredient'] = 'ingredients must be a comma separated list';
}
}
if(array_filter($errors)){
//echo 'errors in the form';
}else{
$id_to_update = mysqli_real_escape_string($conn, $_POST['$id_to_update']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$title = mysqli_real_escape_string($conn, $_POST['title']);
$ingredients = mysqli_real_escape_string($conn, $_POST['ingredients']);
//create SQL
$sql = "UPDATE pizzas SET email='$email', title='$title', ingredients='$ingredients' WHERE id=$id_to_update";
echo $sql;
//save to db and check
if(mysqli_query($conn, $sql)){
//sucess
header('Location: index.php');
}else{
//errors
echo 'query error =' .mysqli_error($conn);
}
}
}
//check GET Request id param
if(isset($_GET['id'])){
$id = mysqli_real_escape_string($conn, $_GET['id']);
// make sql
$sql = "SELECT * FROM pizzas WHERE id = $id";
//get query result
$result = mysqli_query($conn, $sql);
//fetch result in array format
$pizza = mysqli_fetch_assoc($result);
mysqli_free_result($result);
mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html>
<?php include('templates/header.php'); ?>
<section class="container grey-text">
<h4 class="center">Edit Pizza</h4>
<form class="white" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<label >Your Email:</label>
<input type="text" name="email" value="<?php echo htmlspecialchars($pizza['email']); ?>">
<div class="red-text"><?php echo $errors['email']; ?></div>
<label >Pizza Title:</label>
<input type="text" name="title" value="<?php echo htmlspecialchars($pizza['title']); ?>">
<div class="red-text"><?php echo $errors['title']; ?></div>
<label >ingredients(comma separated):</label>
<input type="text" name="ingredients" value="<?php echo htmlspecialchars($pizza['ingredients']); ?>">
<div class="red-text"><?php echo $errors['ingredient']; ?></div>
<div class="center">
<input type="submit" name="update" value="Update Pizza" class="btn brand z-depth-0">
Back
</div>
</form>
</section>
<?php include('templates/footer.php');?>
</html>
Undefined index: $id_to_update in C:\xampp\htdocs\pizza\edit.php on line 36
UPDATE pizzas SET email='ajisafejerry#gmail.com', title='fish Supreme', ingredients='fish, tomatoes, cheese, pepper' WHERE id=query error =You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1

You missed to post the "id" in your form you should add it.
<input type="hidden" name="id_to_update" value="<?php echo $id ?>">
And you have a typo, remove the dollar sign, it is a name not a variable.
$id_to_update = mysqli_real_escape_string($conn, $_POST['id_to_update']);
// ^ here
And if you want, depending on your specifications, you can tweak your redirect after the update to smth. like this.
header('Location: sql.php?id='.$id_to_update);

Related

Can get data on editing part <br /><b>Notice</b>: Undefined variable: row in

I am new in PHP. I keep on getting "undefined variable row in". I already read and try suggestion from other related question and answer here but nothing works for me.
PHP code
<?php
session_start();
require_once('dbConfig.php');
if(isset($_GET['ass_id'])){
$ass_id = $_GET['ass_id'];
$sql = "select * from beedass where ass_id=".$ass_id;
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
$row = mysqli_fetch_assoc($result);
}else{
$errorMsg = 'Could not select a record';
}
}
if(isset($_POST['btnUpdate'])){
$subject = $_POST['subject'];
$date = $_POST['date'];
$content = $_POST['content'];
if(empty($subject)){
$errorMsg = 'Please input subject course';
}elseif(empty($date)){
$errorMsg = 'Please input date to be passed';
}elseif(empty($content)){
$errorMsg = 'Please input assignment content';
}
//check upload file not error than insert data to database
if(!isset($errorMsg)){
$sql = "update beedass
set subject = '".$subejct."',
date = '".$date."',
content = '".$content."'
where ass_id=".$ass_id;
$result = mysqli_query($conn, $sql);
if($result){
$successMsg = 'New record updated successfully';
header('refresh:5;view_beedass.php');
}else{
$errorMsg = 'Error '.mysqli_error($conn);
}
}
}
?>
Keep on getting error on this line on my HTML code:
<form action="edit_beedass.php?ass_id=<?php echo $row['ass_id'];?>"
method="post" enctype="multipart/form-data" class="form-horizontal">
<div class="form-group">
<label for="name" class="col-md-2">Subject Course</label>
<div class="col-md-10">
<input type="text" name="subject" class="form-control" value="<?
php echo $row['subject'] ; ?>">
</div>
</div>
<div class="form-group">
<label for="position" class="col-md-2">Date and Time to be
Passed</label>
<div class="col-md-10">
<input type="text" name="date" class="form-control" value="<?php
echo (isset($row['date']))? $row['date'] : $date ; ?>">
</div>
</div>
<div class="form-group">
<label for="position" class="col-md-2">Assignment Content</label>
<div class="col-md-10">
<input type="text" name="content" class="form-control" value="<?
php echo (isset($row['content'])) ; ?>">
</div>
</div>
The error I get is undefined variable row in echo $row['subject'], echo $row['date'] and echo $row['content'].

Keep user on same page when they click submit on form

Hi the following code below is my comment form. I have included this file comments.php inside my blog posts. When the user clicks submit, they are taken to the blog page rather then kept on the blog article page they are viewing.
I have used this same code for different forms throughout my website, and those pages do not redirect, but rather they stay on the same page when the user clicks submit. Which is the correct way it should be.
I am wondering why this same code on the blog page is being redirected to blog category view when user clicks submit.
How can I prevent the redirection thanks.
<?php
// define variables and set to empty values
$nameErr = $emailErr = $commentErr = "";
$name = $email = $comment = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "First Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
//email
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php
if (count($_POST)>0) echo "<h2>Form Submitted! Thank you <b>$name $lname</b>
for your comment</h2>";
?>
<hr>
<h3 style=" margin-top: 50px; ">Leave a comment</h3>
<h6><span class="error">* All fields required.</span></h6><br /><br />
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input class="form-control" type="text" placeholder="Name*" name="name" value="<?php echo $name;?>" required>
<span class="error"> <?php echo $nameErr;?></span>
<br><br>
</div>
</div>
<!--Email-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input class="form-control" type="email" name="email" placeholder="email address*" value="<?php echo $email;?>"required>
<span class="error"> <?php echo $emailErr;?></span>
<br>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<textarea class="form-control" style="margin-left: 17px;" name="comment" placeholder="Enter a comment*" rows="5" cols="40" required><?php echo $comment;?></textarea>
<br><br>
<div class="g-recaptcha" data-sitekey="6Lc3ZyUUAAAAAIT2Blrg4BseJK9KFc1Rx8VDVNs-"></div><br/>
<input type="submit" name="submit" value="Submit">
</div>
<hr>
</div>
</div>
</form>
<?php
//check if the form has been submitted
if(isset($_POST['submit'])){
/* Attempt MySQL server connection. */
<?php include 'view/conn.php'; ?>
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
mysqli_set_charset($link, "utf8");
// Escape user inputs for security
$Fname = mysqli_real_escape_string($link, $_REQUEST['name']);
$Email = mysqli_real_escape_string($link, $_REQUEST['email']);
$Message = mysqli_real_escape_string($link, $_REQUEST['comment']);
// attempt insert query execution
$sql = "INSERT INTO comments (Name, Email, Comment, Approved) VALUES
('$Fname', '$Email', '$Message', '0')";
if(mysqli_query($link, $sql)){
echo "<p>$Fname Your comment will appear once approved";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
}
?>
<?PHP
$email = $_POST["email"];
$to = "email#email.com";
$subject = "New Email Address for Mailing List";
$headers = "From: $email\n";
$message = "A visitor to your site has posted a comment on a blog post that requires approval.\n
Email Address: $email";
$user = "$email";
$usersubject = "Thank You";
$userheaders = "From: email#email.com\n";
$usermessage = "Thank you for comment at www.oryanm.waiariki.net.nz Geyserland SBA.";
mail($to,$subject,$message,$headers);
mail($user,$usersubject,$usermessage,$userheaders);
?>
<?php
echo "<h2>Comments</h2>";
<?php include 'view/conn.php'; ?>
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM comments WHERE Approved=1 ORDER by id DESC";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<p><b>Comment by:</b> " . $row["Name"]. "</p>" . "<p>" .
$row["Comment"]. "</p> " . "<i><b>Posted:</b> " . $row["Posted"]. "</i><br>
<hr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Instead of php include, I used an iframe as a solution for this issue. Thanks for the help
pass one hidden field in your form
< input type="hidden" value="testRedirect">
and put redirect code on where you are redirect
and put redirect code on where you are redirect
if(isset($_REQUEST["hidden"]))
{
header('Location: http://www.example.com/your_form_view_page ');
exit;
}

Update row data with id not carrying id forward

Have being trying this query for 3 days now. I have a list of rows here: http://prntscr.com/dick00. All what I want to is to edit and delete each row respectively. For some reason the id is not carrying forward and no record is updating.
When I click on edit in access.php I get edit_access.php?id= in address bar.
Here is my link in access.php
<td><a href="edit_access.php?id=<?php echo $row['id']; ?>"><i class="fa fa-edit"></i>edit</td>
edit_access.php
EDIT 1: php code
<?php
// start session
session_start();
// error_reporting(E_ALL); ini_set('display_errors', 1);
if(!isset($_SESSION['user_type'])){
header('Location: index.php');
}
// include connection
require_once('include/connection.php');
// set user session variables
$userId = $_SESSION['user_id'];
$error = [] ;
if(isset($_POST['update']))
{
$id = $_POST['id'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$therapist = $_POST['therapist'];
$access_type = $_POST['access_type'];
$code = $_POST['code'];
$created_at = $_POST['created_at'];
$postcode = $_POST['postcode'];
// validate form field
if (empty($firstname)){
$error[] = 'Field empty, please enter patient first name';
}
if (empty($lastname)){
$error[] = 'Field empty, please enter patient last name';
}
if (empty($therapist)){
$error[] = 'Field empty, please enter your name';
// $error = true;
}
if (empty($code)){
$error[] = 'Field empty, please enter patient access code';
// $error = true;
}
if (empty($access_type)){
$error[] = 'Field empty, please check access type';
// $error = true;
}
if (empty($postcode)){
$error[] = 'Field empty, please enter patient postcode';
// $error = true;
}
//if no errors have been created carry on
if(empty($error)){
$updated_at = date('Y-m-d');
// ************* UPDATE PROFILE INFORMATION ************************//
if(!($stmt = $con->prepare("UPDATE access SET firstname = ?, lastname = ?, therapist = ?, access_type = ?, postcode = ?, code = ?, updated_at = ?
WHERE id = ?"))) {
echo "Prepare failed: (" . $con->errno . ")" . $con->error;
}
if(!$stmt->bind_param('sssssssi', $firstname, $lastname, $therapist, $access_type, $postcode, $code, $updated_at, $userId)){
echo "Binding paramaters failed:(" . $stmt->errno . ")" . $stmt->error;
}
if(!$stmt->execute()){
echo "Execute failed: (" . $stmt->errno .")" . $stmt->error;
}
if($stmt) {
$_SESSION['main_notice'] = '<div class="alert alert-success">"Access Code Added successfully!"</div>';
header('Location: access.php');
exit;
}else{
$_SESSION['main_notice'] = '<div class="alert alert-danger">"Some error, try again"</div>';
header('Location: '.$_SERVER['PHP_SELF']);
}
}
}
// title page
$title = "Edit Access Record | Allocation | The Whittington Center";
// include header
require_once('include/header.php');
?>
<?php
if(isset($_GET['id'])){
$userId = $_GET['id'];
}
else{
$userId = $_POST['user_id'];
// mysqli_close($con);
$stmt = $con->prepare("SELECT * FROM access WHERE id = ?");
$stmt->bind_param('s', $userId);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows == 0) {
echo 'No Data Found for this user';
}else {
$stmt->bind_result($firstname, $lastname, $therapist, $access_type, $postcode, $code);
while ($row = $stmt->fetch());
$stmt->close();
}
?>
EDIT 2: HTML part
<h2 class="text-light text-greensea">Edit Access Record</h2>
<form name="access" class="form-validation mt-20" novalidate="" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" autocomplete='off'>
<div class="form-group">
<input type="text" name="firstname" class="form-control underline-input" value='<?php if(isset($error)){ echo $_POST[' firstname ']; } ?>' placeholder='firstname'></td>
</div>
<div class="form-group">
<input type="text" name="lastname" class="form-control underline-input" value='<?php if(isset($error)){ echo $_POST[' lastname ']; } ?>' placeholder='lastname'></td>
</div>
<div class="form-group">
<input type="text" name="therapist" class="form-control underline-input" value='<?php if(isset($error)){ echo $_POST[' therapist ']; } ?>' placeholder='therapist'></td>
</div>
<?php $access_type = $access_type; ?>
<div class="form-group ">
<label for="work status">Access Type</label>
<div name="access_type" value='<?php if(isset($error)){ echo $_POST[' access_type ']; } ?>'>
<label class="checkbox-inline checkbox-custom">
<input type="checkbox" name="access_type" <?php if (isset($work_status) && $access_type == "Keysafe") echo "checked"; ?> value="Keysafe"><i></i>Keysafe
</label>
<label class="checkbox-inline checkbox-custom">
<input type="checkbox" name="access_type" <?php if (isset($access_type) && $access_type == "keylog") echo "checked"; ?> value="keylog"><i></i>Keylog
</label>
</div>
</div>
<div class="form-group">
<input type="text" name="code" class="form-control underline-input" value='<?php if(isset($error)){ echo $_POST[' code ']; } ?>' placeholder='access code'></td>
</div>
<div class="form-group">
<input type="text" name="postcode" class="form-control underline-input" value='<?php if(isset($error)){ echo $_POST[' postcode ']; } ?>' placeholder='postcode'></td>
</div>
<div class="form-group text-left mt-20">
<button type="update" class="btn btn-primary pull-right" name="update" id='update'>Add Access</button>
<!-- <label class="checkbox checkbox-custom-alt checkbox-custom-sm inline-block">
<input type="checkbox"><i></i> Remember me
</label> -->
<a href="access.php">
<button type="button" class="btn btn-greensea b-0 br-2 mr-5">Back</button>
</a>
</div>
</form>
</div>
<!-- end of container -->
Thanks guy's for requesting for more code... i hope have given enough code sample.
you most put your id inside of a hidden input in your html form like this:
<input type="hidden" name="itemId" value="<?php echo '$_GET['id']'?>">
and then when you submit your form you have itemId in side $_POST['itemId'] variable.
EDIT:
I must describe scenario for you. maybe you got the point.
you have a list of access witch in every row has this tag:
access ....
in your access-form.php you have a form with this structure:
<form method="post" action="edit-access.php">
.....
<input type="hidden" name="id" value="<?php echo $_GET['id']?>">
.....
</form>
next in your edit-access.php you can access to this id by this syntax:
echo $_POST['id'];

Data ain't changed after submitted to mysql

i have a code for updating data to myql. It looks doesn't have a problem but it ain't changed
my update code :
//previous data//
....
if (isset($_POST['update'])) {
$nim = mysqli_real_escape_string($connection, ($_POST['nim']));
$name = mysqli_real_escape_string($connection, ($_POST['name']));
$class1 = mysqli_real_escape_string($connection, ($_POST['class2']));
$class2 = mysqli_real_escape_string($connection, ($_POST['class1']));
if (!preg_match("/^[1-9][0-9]*$/",$nim)) {
$error = true;
$nim_error = "NIM only contain numbers";
}
if (!preg_match("/[^a-zA-Z]/",$name)) {
$error = true;
$name_error = "NIM only contain numbers";
}
if (!preg_match("/^[1-9][0-9]*$/",$class1)) {
$error = true;
$class1_error = "Class only contain numbers";
}
if (!preg_match("/^[1-9][0-9]*$/",$class1)) {
$error = true;
$class2_error = "Class only contain numbers";
}
$result = "UPDATE users SET nim='$nim', name='$name', class1='$class1', class1='$class1' WHERE id='$id'";
mysqli_query($connection, $result);
}
?>
and this is my html code :
<div id="popup2" class="overlay">
<div class="popup">
<h2 class="range2">Edit</h2>
<a class="close" href="#">×</a>
<div class="content">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input class="input" type="text" name="nim" placeholder="NIM" required/>
<input class="input" type="text" name="name" placeholder="Name" required/>
<i>SK</i>
<input class="input1" type="text" name="class1" placeholder="00" required/>
<i>-</i>
<input class="input1" type="text" name="class2" placeholder="00" required/>
<input name="update" type="submit" class="button" id="submit" value="Submit">
</form>
</div>
</div>
</div>
is there any wrong code ? Thank you..
It is really hard to explain: Take a look.
If you want to update a single data you will need a identity(Primary
key). That mean which data you want to update.
Below Example: check index.php file
In file index.php change dbname to your database name in connection.
browse project_url/index.php?id=1 [here use any id from your database]
Then update your data.
index.php
//Show existed data againist id
if(isset($_GET['id'])){
$id = $_GET['id'];
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(array('id'=>$id));
$data = $stmt->fetch();
if (empty($data)) {
echo "No data found in user table. Use proper ID.";
}
}
//Update query
$msg = array();
if (isset($_POST['id']) && $_POST['id']!='') { //operation is update, because id exist
if($_POST['nim']!=0 && is_numeric($_POST['nim'])){
$nim = $_POST['nim'];
}else{
$msg[]="Nim only can be number";
}
if($_POST['name']!=''){
$name = $_POST['name'];
}else{
$msg[]="came only can not be empty";
}
if(is_numeric($_POST['class1'])){
$class1 = $_POST['class1'];
}else{
$msg[]="Class1 only can be number";
}
if(is_numeric($_POST['class2'])){
$class2 = $_POST['class2'];
}else{
$msg[]="Class1 only can be number";
}
$id = $_POST['id'];
if(count($msg)==0){
$stmt = $pdo->prepare('UPDATE users SET nim=:nim, name=:name, class1=:class1, class2=:class2 WHERE id=:id');
$result = $stmt->execute(array(
'nim' => $nim,
'name' => $name,
'class1'=> $class1,
'class2'=> $class2,
'id' => $id,
));
if($result){
echo "successfully updated.";
}else{
echo "update failed";
}
}
}else{
//You can run here insert operation because id not exist.
echo "Id not set";
}
?>
<div id="popup2" class="overlay">
<div class="popup">
<h2 class="range2">Edit</h2>
<a class="close" href="#">×</a>
<div class="content">
<?php foreach ($msg as $value) {
echo $value."<br>";
}?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php if(isset($data)){?>
<input class="input" type="hidden" name="id" value="<?php echo $data['id']; ?>" />
<?php } ?>
<input class="input" type="text" name="nim" value="<?php echo isset($data)?$data['nim']:''?>" placeholder="NIM" required/>
<input class="input" type="text" name="name" value="<?php echo isset($data)?$data['name']:''?>" placeholder="Name" required/>
<i>SK</i>
<input class="input1" type="text" name="class1" value="<?php echo isset($data)?$data['class1']:''?>" placeholder="00" required/>
<i>-</i>
<input class="input1" type="text" name="class2" value="<?php echo isset($data)?$data['class2']:''?>" placeholder="00" required/>
<input name="update" type="submit" class="button" id="submit" value="Submit">
</form>
</div>
</div>
</div>
My friend,
only do one thing to resolve this
echo $result = "UPDATE users SET nim='$nim', name='$name', class1='$class1', class1='$class1' WHERE id='$id'";
die;
then submit your form again and you will get your static query into your page then just copy that query and try to run into phpmyadmin then you will get your actual error.

PHP ignoring if statements

I am having a very weird problem here, my if else statements just get ignored after I submit the form and all values entered or not entered goes through to the database.
Firstly, I pre populate all fields with info submitted during registration then users can edit and change their info - this works fine but I decided to add it as I don't know whether it might have a hand in this mystery error.
Here's my code to retrieve details, the variables holding retrieved values are echoed in their respective fields in the form.
<?php
include("connect.php");
$results = $conn->query("SELECT username, first_name,last_name, email,phone,address FROM users WHERE email='$user_logged'");
while ($row = $results->fetch_assoc()) {
$u_name = $row['username'];
$f_name = $row['first_name'];
$l_name = $row['last_name'];
$email = $row['email'];
$phone = $row['phone'];
$address = $row['address'];
}
$results->free();
$conn->close();
?>
It's not checking for empty fields. Functions test_input and preg_match do not work alsko. The form just submits and database gets updated.
I have spent 2 days going through to look for where the error might be but I can't detect it.
<?php
$user_logged = $_SESSION['logged_in'];
if (isset($_POST['btnUpdate'])) {
include("connect.php");
$phoneErr = $f_nameErr = $l_nameErr = "";
$user_email = $first_name = $last_name = $phone_upadate = $address_updated = "";
if (empty($_POST["fname"])) {
$f_nameErr = "First Name is required";
} else {
$first_name = test_input($_POST["fname"]);
if (!preg_match("/^[a-zA-Z ]*$/", $first_name)) {
$f_nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["lname"])) {
$l_nameErr = "Last Name is required";
} else {
$last_name = test_input($_POST["lname"]);
if (!preg_match("/^[a-zA-Z ]*$/", $last_name)) {
$l_nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["phone"])) {
$phoneErr = "Phone No is required";
} else {
$phone_upadate = test_input($_POST['phone']);
if (!preg_match("/^[0-9]{0,18}$/", $phone_upadate)) {
$phoneErr = "Only numbers and white space allowed";
}
}
$user_email = $_POST['email'];
$address_updated = $_POST['txtaddress'];
$results = $conn->query("UPDATE users SET
first_name='$first_name',last_name='$last_name',
email='$user_email',phone='$phone_upadate',
address='$address_updated'
WHERE email='$user_logged'");
if ($results) {
header("Location: edit-info.php");
} else {
print 'Error : (' . $conn->errno . ') ' . $conn->error;
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Here is my html code
<form action="edit-info.php" method="POST">
<?php $username_error="can't be changed"; ?>
<p>Username</p>
<p><input type="text" name="username" id="txtuser" value="<?php echo $u_name; ?>" readonly></input><span id="error"><?php echo $username_error?></span></p>
<p>First Name</p>
<p><input type="text" name="fname" id="txtuser" value="<?php echo $f_name; ?>"></input><span id="error"><?php echo $f_nameErr;?></span></p>
<p>Last Name</p>
<p><input type="text" name="lname" id="txtuser" value="<?php echo $l_name; ?>" ></input><span id="error"><?php echo $l_nameErr;?></span></p>
<p>Email</p>
<p> <input type="text" name="email" id="txtuser" value="<?php echo $email; ?>" readonly></input><span id="error"><?php echo $f_nameErr;?></span></p>
<p>Phone</p>
<p><input type="text" name="phone" id="txtuser" value="<?php echo $phone; ?> " ></input></p>
<span id="error"><?php echo $phoneErr;?></span>
<p>Address</p>
<p><textarea id="txtaddress" name="txtaddress" cols="40" rows="10" ><?php echo $address; ?></textarea></p>
<p><input type="submit" name="btnUpdate" value="UPDATE" /></p>
</form>
You need to check the values of $phoneErr, $f_nameErr, $l_nameErr before you proceed UPDATE like this
if(empty($phoneErr) && empty($f_nameErr) && empty($l_nameErr)){
$results = $conn->query("UPDATE users SET first_name='$first_name',last_name='$last_name', email='$user_email',phone='$phone_upadate',address='$address_updated' WHERE email='$user_logged'");
}
Because when you have any validation error in empty or preg_match you are updating these values. And without checking these $phoneErr, $f_nameErr, $l_nameErr variables you are proceeding to UPDATE
You could try replacing
"/^[a-zA-Z ]*$/"
with
"/^[a-zA-Z ]+$/"
Notice we are replacing the multiplication sign with a summation sign.

Categories