I am trying to create a page to allow users to edit their details using PHP, which validates the content before being submitted. I want to allow users to update their username, first and second name and email address.
The validation consists of:
<?php
if(preg_match("/^[0-9a-zA-Z_]{3,}$/", $_POST["username"]) == 0)
$error_username = '<li>Usernames may contain only digits, upper and lower case letters and underscores</li>';
if(preg_match("/^[A-Za-z]+$/", $_POST["fname"]) == 0)
$error_fname = '<li>First Name may contain upper and lower case letters</li>';
if(preg_match("/^[A-Za-z]+$/", $_POST["sname"]) == 0)
$error_sname = '<li>Second Name may contain upper and lower case letters</li>';
if(preg_match("/^[a-zA-Z]\w+(\.\w+)*\@\w+(\.[0-9a-zA-Z]+)*\.[a-zA-Z]{2,4}$/", $_POST["email"]) == 0)
$error_email = '<li>Email Addresses must have a valid email address format</li>';
else header("Location: edit.php");
?>
And to display the errors:
<ul>
<?php if(isset($error_username)) echo $error_username; ?>
<?php if(isset($error_fname)) echo $error_fname; ?>
<?php if(isset($error_sname)) echo $error_sname; ?>
<?php if(isset($error_email)) echo $error_email; ?>
</ul>
The form that I have is:
<form name="edit_account" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input class="form_field" name="username" type="text" value="<?php echo $_POST["username"]; ?>" placeholder="Username">
<input class="form_field" name="fname" type="text" value="<?php echo $_POST["fname"]; ?>" placeholder="First Name">
<input class="form_field" name="sname" type="text" value="<?php echo $_POST["sname"]; ?>" placeholder="Second Name">
<input class="form_field" name="email" type="text" value="<?php echo $_POST["email"]; ?>" placeholder="Email Address">
<input type="submit" name="Submit" value="Update Account">
</form>
Providing that all requirements of the validation are met, the user is taken to edit.php and then redirected to a success page:
<?php
$sql = $mysqli;
$id = htmlentities($_SESSION['user_id']);
$username = $sql->real_escape_string($_POST['username']);
$fname = $sql->real_escape_string($_POST['fname']);
$sname = $sql->real_escape_string($_POST['sname']);
$email = $sql->real_escape_string($_POST['email']);
$query = ("
UPDATE users
SET
username='$username',
fname='$fname',
sname='$sname',
email='$email'
WHERE id='$id'") ;
$sql->query($query) or die($query.'<br />'.$sql->error);
header ('Location: success.php');
?>
When I attempt to run this code, the updating fields are submitted into the database as blanks - However, without the validation, the users submitted details are successfully entered.
Can someone please point out what is causing the form to submit as a blank. Thanks.