Using Sessions To Remember User on PHP Form - php

Intro: I'm trying to learn PHP on $_SESSION. What I was trying to do is call the value assigned through sessions that when you close your tab will keep the value assigned and echoes it on the browser when you open a tab in the browser.
Issue: There's something wrong with my code where for some reason I couldn't echo the value entered in on a form.
The form looks like this:
Name:_____________
Email:_____________ Remember me? __ SUBMIT
I made it so that $_SESSION['name'] = "John" and $_SESSION['email'] = "someemail#email.com" only when user click on "remember me".
If you close a "tab" on the browser but not the browser itself should echo...
John
someemail#email.com
Here's your download link (some link here)...
But of course if you close the browser, session is lost. Cookies can be used but I'm working on sessions to learn more.
Below's code runs but for some reason I couldn't echo values from $_SESSION variables.
<?php
//Start session
session_start();
// session
if (isset($_POST['remember'])) {
$customer_name = $_SESSION['name'];
if (!($customer_name)) {
$customer_name = $_POST['name'];
}
$customer_email = $_SESSION['email'];
if (!($customer_email)) {
$customer_email = $_POST['email'];
}
}
//If form submit validate
if (isset($_POST['Submit'])) {
// Santize fields here but FILTER_VALIDATE_STRING isn't necessary as there is no absolute way
//to validate names absolutely
// Also shows error message if there's error
if ($_POST['name'] != "") {
$_POST['name'] = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
if ($_POST['name'] == "") {
$errors .= 'Please enter a valid first name.<br/><br/>';
}
} else {
$errors .= 'Please enter your first name.<br/>';
}
// Sanitize and validate email
// Error message shows if any
if ($_POST['email'] != "") {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors .= "$email is NOT a valid email address.<br/><br/>";
}
} else {
$errors .= 'Please enter your email address.<br/>';
}
// If no errors, submitted form is emailed
if (!$errors) {
echo "I did something!<br /><br />"; // might add some message
//downloadLink();
echo "<br /><br />";
}
} else {
echo '<div id="error">' . $errors . '<br /></div>';
}
?>
<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Name:
<?php
if (isset($_SESSION['name'])) {
echo $_SESSION['name']."<br />";
}
else {
?>
<input type="text" name="name" value="<?php echo $_POST['name']; ?>" size="25" /><br />
<?php } ?>
Email:
<?php
if (isset($_SESSION['email'])) {
echo $_SESSION['email']."<br /><br />";
// echo link.. downloadLink();
}
else {
?>
<input type="text" name="email" value="<?php echo $_POST['email']; ?>" size="25"/>
<input type="checkbox" name="remember" /> Remember me
<input type="submit" name="Submit" />
<?php } ?>
</form>
</div>

Put this at the beginning under session_start();
if (!isset($_SESSION['name'])) {
echo "Your session is not good";
} else { echo "Session is set";
}
then replace $customer_name = $_SESSION['name']; with $_SESSION['name']=$_POST['remember']; and you will start getting results.

Related

php validation on submit when jump from one page to another

In this program when i am clicking submit button the page directly goes on other page 2222.php. The error message not pop up.. I just want hit error message when clicking on submit button...
php_validation.php
<?php
// Initialize variables to null.
$nameError ="";
$emailError ="";
$genderError ="";
$name = $email = $gender ="";
// On submitting form below function will execute.
if(isset($_POST['submit']))
{
if (empty($_POST["name"])) //---------------------------------------------- -------------------------
{
$nameError = "Name is required";
}
else
{
$name = test_input($_POST["name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameError = "Only letters and white space allowed";
}
//-----------------------------------------------------------------------
}
if (empty($_POST["email"])) //---------------------------------------------- -------------------------
{
$emailError = "Email is required";
}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid or not
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailError = "Invalid email format";
}
}
//-----------------------------------------------------------------------
if (empty($_POST["gender"]))
{
$genderError = "Gender is required";
}
else
{
$gender = test_input($_POST["gender"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" name="myForm" action="2222.php">
<p>First Name:
<input type="text" name="fname" id="fname" />
<span class="error">* <?php echo $nameError;?></span>
</p>
<br><br>
<p>
Email:
<input type="text" name="email" id="email">
<span class="error">* <?php echo $emailError;?></span>
</p>
<br><br>
<p>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">*<?php echo $genderError;?></span><br><br />
</p>
<input class="submit" type="submit" name="submit" value="Submit" >
</form>
</body>
2222.php
<?php
$name = $_POST['fname'];
$email = $_POST['email'];
$radio = $_POST['gender'];
echo "<h2>Your Input:</h2>";
echo "user name is: ".$name;
echo "<br>";
echo "user email is: ".$email;
echo "<br>";
echo "user is ".$radio;
?>
So I've done a quick code for you :
Here is your "php_validation.php" :
<?php
//Init error var
$nameError = '';
$emailError = '';
$genderError = '';
//Did we have an error ?
if(isset($_GET['error'])){
//Split error return into an array
$errorList = explode('_', $_GET['error']);
//Verify every possible error
if(in_array('name',$errorList)){
$nameError = 'Please enter your name<br>';
}
if(in_array('email',$errorList)){
$emailError = 'Please enter your email<br>';
}
if(in_array('gender',$errorList)){
$genderError = 'Please enter your gender';
}
}
?>
I didnt changed the form
Then this is your "2222.php" :
<?php
$error ='';
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//When we receive data
if(isset($_POST)){
//Verify all possible data and set error
if(!empty($_POST['fname'])){
$name = test_input($_POST['fname']);
}else{
$error .= 'name_';
}
if(!empty($_POST['email'])){
$email = test_input($_POST['email']);
}else{
$error .= 'email_';
}
if(!empty($_POST['gender'])){
$radio = test_input($_POST['gender']);
}else{
$error .= 'gender_';
}
//if we have an error then redirect to form with error
if(!empty($error)){
header("Location:php_validation.php?error=".$error);
}
}
?>
Didnt changed your output on this page either.
So as I said previously when you here is what happend when you click the submit button :
Submit Click
Form sent to 2222.php as $_POST and you're redirected to this page
There is no way that could be working if your form is posting on an other page than the one where the check is made.
Since your form's action is "2222.php", on click the submit button will automatically redirect you to 2222.php before doing anything.
If you want to check what you've received by your form, you can do it in your "2222.php", then redirect it with the error message to php_validation.php
You could do one of the following things:
Do all the checking in Javascript "onClick" function
Do Ajax call "onClick" to a handler page, get the validation message from that page.
Do the validation on "2222.php" page
action back to the same page (since you are doing some validation here) and redirect after validation on "2222.php" page
Now depends only on you which fits your program.
If you want to stay on the same page you could submit the form to an iframe, as the results of the processing script would be displayed in the iframe itself.
Example:
files:
file-with-form.php
form-submit-processing-file.php
Code examples:
file-with-form.php
<!DOCTYPE html>
<html>
<head>
<title>[Your page title]</title>
</head>
<body>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<!-- Form -->
<form action="[path-to-form-submit-process]" method="[GET|POST]"
target="form-processor">
<div>
<label>First Name:
<input type="text" name="fname" id="fname" />
<span class="error">* <?php echo $nameError ?></span>
</label>
</div>
<div>
<label>Email:
<input type="text" name="email" id="email">
<span class="error">* <?php echo $emailError ?></span>
</label>
</div>
<div>
<label>Gender:
<p><input type="radio" name="gender" value="female"> Female</p>
<p><input type="radio" name="gender" value="male"> Male</p>
<p><span class="error">*<?php echo $genderError ?></span></p>
</label>
<input class="submit" type="submit" name="submit" value="Submit" >
</div>
</form>
<!-- The iframe to submit the form to -->
<iframe name="form-processor" id="form-processor"
src="[path-to-form-submit-process]"></iframe>
<!--
NOTE: The error message spans are left there just because you had them
in your code, those will not work here at this point, actually depending
on your php configuration will most probably throw errors/warnings,
because such variables were not defined at all...
-->
</body>
</html>
As:
[path-to-form-submit-process] - a placeholder to be replaced with the URL to the file/ Controller -> Action that would process the passed form data
[*] - placeholders that should be replaced with the values for your case
form-submit-processing-file.php
<?php
# Processing the form fields and displaying the messages
$post = $_POST;
# Preprocessing the passed data
// Here you would filter out data from the $_POST superglobal variable
# Validating the passed data
// Check if the data entries, e.g.
// Flag for error risen - does not let the process to be completed
$invalidFormData = false;
$messages = [];
function addErrorMessage($message, &$messages, &$errorFlag)
{
$errorFlag = true;
$errorMessageTemplate = '<p class="error-message">{message}</p>';
array_push($messages, str_replace('{message}', $message,
$errorMessageTemplate));
}
// Validating the email
$email = array_key_exists('email', $post)
? $post['email']
: null;
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
// Raising the flag for an error on validation
addErrorMessage("$email is not a valid email address", $messages, $invalidFormData);
}
// ........
// validation of rest of fields
// ........
$internalError = false;
# Some business logic after the validation, recording more messages etc.
try {
// ........
} catch (Exception $e) {
$internalError = true;
}
# Stop execution on internal error
if ($internalError === true)
{
?>
<h2>Sorry, there's an error on our side... we'll do all in our
powers to fix it right away!</h2>
<?php
exit;
}
# Displaying the results
if ($invalidFormData === true) {
// Building errors message
$messagesHeading = '<h2>There were problems submitting your data. :/</h2>';
} else {
$messagesHeading = '<h2>Your data was successfully submitted! Yay!</h2>';
}
// Placing the heading in front of other messages
array_unshift($messages, $messagesHeading);
// Displaying the messages:
echo implode('', $messages);
However I believe this should be done via an AJAX call insted.
Also there are a lot of bad practices in this case, so I would suggest checking out some design patterns and architectures as MVC for instance and consider using a framework like Symfony/Laravel/CodeIgniter... There are a lot of tools that will make your life easier :)

Clear form fields after a successful submit

well im working on a small html form.
<form class="contact" action="" method="POST">
<label>Name : </label><input type="text" name="name" value="<? echo $name; ?>"/>
<p class="middle"><label>Comment : </label><textarea name="message"></textarea><? echo $message; ?></p>
<label class="captcha"><img src="captcha.php" style="line-height: 30px;"></label><input type="text" name="code"/>
<input type="submit" class="csubmit" value="Now !" name="get"/>
</form>
and this is the php code:
<?php
if (isset($_POST['get'])) {
$error = "";
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$error .= "no name. <br />";
}
if (!empty($_POST['message'])) {
$message = $_POST['message'];
} else {
$error .= "no message <br />";
}
if(($_POST['code']) == $_SESSION['code']) {
$code = $_POST['code'];
} else {
$error .= "wrong captcha <br />";
}
if (!empty($error)) {
echo '<p class="error">Error :<br/>' . $error . '</p>';
} elseif (!empty($success)) {
echo $success;
}
if (empty($error)) {
$message = mysql_real_escape_string($message);
$name = mysql_real_escape_string($name);
$id = mysql_real_escape_string($_GET['id']);
$date = date("Y-m-d H:i:s");
mysql_query("INSERT INTO comments(id, name, comment, time,approved)VALUES('$id', '$name', '$message', '$date', '0')");
echo "thank you";
}
}
?>
As you can see i user $message and $name to keep informations after a submit with wrong captcha code, but the problem is that i want to clear those fields after a submit with correct informations. Can you please tell me how can i clear form fields after a succesfull submit ?
You can use .reset() on your form.
$("#form")[0].reset();
You could follow that with Javascript too
document.getElementById('form').reset();
Or, if successful, redirect the user back to your contact page:
header("Location: contact.php"); // redirect back to your contact form
exit;
EDIT
<input type="submit" class="csubmit" value="Now !" name="get" onClick="clearform();" />
function clearform()
{
document.getElementById("name").value=""; //don't forget to set the textbox ID
document.getElementById("message").value=""; //don't forget to set the textbox ID
document.getElementById("code").value=""; //don't forget to set the textbox ID
}
Also use:
required="required"
so people will be required to fill out the input fields :)
Which by the way is the prefered method. If you keep the user in a page that was reached through a POST method, if he refreshes the page the form will be submitted again.

PHP form verification

I'm new to PHP so please be gentle!
I'm trying to build a simple PHP form validation with an error message/confirm message. When I submit the form, it's supposed to check if fields are empty and display the corresponding message. But it keeps giving me an error and I have no idea why:
Parse error: syntax error, unexpected T_IF in process.php on line 6
Here's process.php code:
<form action="process.php" method="post">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
E-mail: <input type="text" name="email"><br>
<input type="hidden" name="submitted" value="1">
<input type="submit">
</form>
<?php
//If form was submitted
if ($_POST['submitted']==1) {
$errormsg = ""; //Initialize errors
if ($_POST[fname]){
$fname = $_POST[fname]; //If fname was entered
}
else{
$errormsg = "Please enter first name";
}
if ($_POST[lname]){
$lname = $_POST[lname]; //If lname was entered
}
else{
if ($errormsg){ //If there is already an error, add next error
$errormsg = $errormsg . ", last name";
}
else{
$errormsg = "Please enter last name";
}   
}
if ($_POST[email]){
$email = $_POST[email]; //If email was entered
}
else{
if ($errormsg){ //If there is already an error, add next error
$errormsg = $errormsg . " & email";
}else{
$errormsg = "Please enter email";
}
}
}
if ($errormsg){ //If any errors display them
echo "<div class=\"box red\">$errormsg</div>";
}
//If all fields present
if ($fname && $lname && $email){
//Do something
echo "<div class=\"box green\">Form completed!</div>";
}
?>
You forgot to add " on post array that is the reason for your error $_POST[lname] change to $_POST['lname']; . Pass string to your $_POST[];
if ($_POST["fname"]){
$fname = $_POST[fname]; //If fname was entered
}
else{
$errormsg = "Please enter first name";
}
if ($_POST["lname"]){
$lname = $_POST[lname]; //If lname was entered
}
else{
if ($errormsg){ //If there is already an error, add next error
$errormsg = $errormsg . ", last name";
}
else{
$errormsg = "Please enter last name";
}
}
if ($_POST["email"]){
$email = $_POST["email"]; //If email was entered
}
Some of your $_POST variables were missing single quotation marks, which is probably what caused the errors. However, generally speaking, there are other code suggestions which I've layed out.
I restructured your code to be more scalable and follow better practice with the following enhancements:
Form values will remember their previous value and not erased on each post.
Removed the 'submitted' field and replaced with if (!empty($_POST)) {} to make sure form was posted.
Moved error messages into an array. This is more maintainable and readable to my taste (imagine having 15+ fields to test for).
Added validate() function to run on your validation tests.
Removed variable assignments ($fname = $_POST['fname']) since they were not used except for the validation, which can access them directly.
Moved all tests inside the main if statement.
Hope this helps!
<form action="process.php" method="post">
First Name: <input type="text" name="fname" value="<?php echo isset($_POST['fname']) ? $_POST['fname'] : ''?>"><br>
Last Name: <input type="text" name="lname" value="<?php echo isset($_POST['lname']) ? $_POST['lname'] : ''?>"><br>
E-mail: <input type="text" name="email" value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''?>"><br>
<input type="submit">
</form>
<?php
//If form was submitted
if (!empty($_POST)) {
$errors = array();
if (empty($_POST['fname'])){
$errors[] = 'First name must be entered.';
}
if (empty($_POST['lname'])){
$errors[] = 'Last name must be entered.';
}
if (empty($_POST['email'])){
$errors[] = 'Email address must be entered.';
}
if ($errors){ //If any errors display them
$error_msg = implode('<br>',$errors);
echo "<div class=\"box red\">$error_msg</div>";
}
//If all fields present
elseif (validate()){
//Do something
echo "<div class=\"box green\">Form completed and validated!</div>";
}
}
function validate() {
/*you can run all your validation methods here, such as check for length, regexp email verification, etc.*/
$validated = false;
if ($_POST['fname'] && $_POST['lname'] && $_POST['email']) {
$validated = true;
}
return $validated;
}
?>
For the $_POST variables use syntax as $_POST['your variable name']
I corrected your code as below:
<form action="test.php" method="post">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
E-mail: <input type="text" name="email"><br>
<input type="hidden" name="submitted" value="1">
<input type="submit">
</form>
<?php
//If form was submitted
if ($_POST['submitted']==1) {
$errormsg = ""; //Initialize errors
if ($_POST['fname']){
$fname = $_POST['fname']; //If fname was entered
}
else{
$errormsg = "Please enter first name";
}
if ($_POST['lname']){
$lname = $_POST['lname']; //If lname was entered
}
else{
if ($errormsg){ //If there is already an error, add next error
$errormsg = $errormsg . ", last name";
}
else{
$errormsg = "Please enter last name";
}
}
if ($_POST['email']){
$email = $_POST['email']; //If email was entered
}
else{
if ($errormsg){ //If there is already an error, add next error
$errormsg = $errormsg . " & email";
}else{
$errormsg = "Please enter email";
}
}
}
if ($errormsg){ //If any errors display them
echo "<div class=\"box red\">$errormsg</div>";
}
//If all fields present
if ($fname && $lname && $email){
//Do something
echo "<div class=\"box green\">Form completed!</div>";
}
?>
As Ohgodwhy said,
You need to change every existence of $_POST[word] to $_POST['word']. Note the '.
And why are you using <input type="hidden" name="submitted" value="1">, this is not a good practice. Better use.
if($_SERVER['REQUEST_METHOD'] == "POST")
The issue here is a lack of register globals being enabled (which is a good thing in my eyes) and not using proper string encapsulation.
You need to change every existence of $_POST[word] to $_POST['word']. Note the '.
I am Using thing type of simple validation. Here is my javascript code:
var ck_name = /^[A-Za-z0-9 ]{3,50}$/;
var ck_email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;
var ck_mob = /^[0-9 ]{8,11}$/;
function validate(form){
var name = form.name.value;
var email = form.email.value;
var mob = form.mob.value;
var errors = [];
if (!ck_name.test(name))
{
errors[errors.length] = "Your valid Name .";
}
if (!ck_email.test(email))
{
errors[errors.length] = "Your must enter a valid email address.";
}
if (!ck_mob.test(mob))
{
errors[errors.length] = "Your valid Mobile Number.";
}
if (errors.length > 0)
{
reportErrors(errors);
return false;
}
return true;
}
function reportErrors(errors)
{
var msg = "Please Enter Valide Data...\n";
for (var i = 0; i<errors.length; i++)
{
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}

How do I submit a form's data automatically after successful PHP validation?

This is what I did in a nutshell:
<?php
// define variables and initialize with empty values
//error variables
$agentNameErr = "";
//non-error variables
$agentemail = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["agentname"])) {
$agentNameErr = "Missing";
}
else {
$agentname = $_POST["agentname"];
}
}
// form
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" >
<input name="agentname" type="text" id="agentname" autocomplete="on" placeholder="Agent Name" value= "<?php echo htmlspecialchars($agentname);?>" />
//only shows up if $agentNameErr is assigned the value of "Missing"
<span class="error"><?php echo $agentNameErr;?></span>
</form>
It checks if $agentname is erroneous (blank). If it's not blank, I don't know how to proceed. I want it to just automatically submit all the information without any additional user input to a review page so the user can see if the name was spelled correctly. And then they can do a final submission.
I don't know MySQL.
In normal english:
//user presses the submit button
if ($agentname has error)
stay on page and display errors
else
submit automatically to next page (order review page for visual checking)
What do I do to "submit automatically to next page"?
Use a php session.
if ($agentname has error)
stay on page and display errors
else
{
$_SESSION['key1'] = 'something'
$_SESSION['key2'] = 'something else'
...
header('location: ' . $next_page);
}
If you don't know how to use php sessions see the examples here
Try this:
<?php
$agentNameErr = "";
$agentemail = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["agentname"])) {
$agentNameErr = "Missing";
} else {
$agentname = $_POST["agentname"];
header("Location: nextpage.php?agent=".$agentname);
}
} else {
?>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" >
<input name="agentname" type="text" id="agentname" autocomplete="on" placeholder="Agent Name" value= "<?php echo htmlspecialchars($agentname);?>" />
//only shows up if $agentNameErr is assigned the value of "Missing"
<?php if(!empty($agentNameErr)) { ?>
<span class="error"><?php echo $agentNameErr;?></span>
<?php } ?>
</form>
<?php } ?>
Keep it simple. Capture the entire contents of the form and store in a session variable.
$agentNameErr = '';
$agentemail = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (empty($_POST['agentname'])) {
$agentNameErr = 'Missing';
} else {
$_SESSION['agent-form'] = $_POST;
// Move to next page
header('Location: nextpage.php');
exit;
}
}
Once forwarded to the next page you can access the form data from the session variable.
// Entire contents of form
print_r($_SESSION['agent-form']);
// "agentname" data
print_r($_SESSION['agent-form']['agentname']);

Trouble with my PHP validation script

So I have created a PHP validation script. On test I filled and submitted the forms but so far $error returns undefined index and no data is set into the database. Can anyone take a look and give a second opinion on why its not functioning as intended? To my eye it all looks OK.
Otherwise my script runs OK (Insert into DB) it's just something about my validation script breaks it.
<?php
if (isset($_POST['Submit'])) {
if ($_POST['name'] != "") {
$_POST['name'] = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
if ($_POST['name'] == "") {
$errors .= 'Please enter a valid name.<br/><br/>';
}
} else {
$errors .= 'Please enter a name.<br/>';
}
if (isset($_POST['Submit'])) {
if ($_POST['address'] != "") {
$_POST['address'] = filter_var($_POST['address'], FILTER_SANITIZE_STRING);
if ($_POST['address'] == "") {
$errors .= 'Please enter a valid address<br/><br/>';
}
} else {
$errors .= 'Please enter a address.<br/>';
}
if (isset($_POST['postcode'])) {
if ($_POST['postcode'] != "") {
$_POST['postcode'] = filter_var($_POST['postcode'], FILTER_SANITIZE_STRING);
if ($_POST['postcode'] == "") {
$errors .= 'Please enter a valid name.<br/><br/>';
}
} else {
$errors .= 'Please enter a name.<br/>';
}
if (!$errors) {
$name = $_POST['name'];
$address = $_POST['address'];
$postcode = $_POST['postcode'];
$photo = $_POST['photo'];
$db1 = new dbmember();
$db1->openDB();
$numofrows = $db1->insert_member('', $name, $address, $postcode, $photo);
echo "Success. Number of rows affected:
<strong>{$numofrows}<strong>";
$sql="SELECT * from member";
$result=$db1->getResult($sql);
echo "<table class='table table-hover'>";
echo "<tr><th>Member ID</th><th>Name</th><th>Address</th><th>Postcode</th><th>Photo</th></tr>";
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>{$row['mid']}</td><td>{$row['name']}</td>";
echo "<td>{$row['address']}";
echo "<td>{$row['postcode']}";
echo"<td><img height='80' width='120' src='{$row['photo'] }' /></td>";
echo "</tr>";
}
echo "</table>";
$db1->closeDB();
}
}
}
}
echo "Records updated!<br/><br/>";
} else {
echo '<div style="color: red">' . $errors . '<br/></div>';
}
?>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post" name="myform" class = "well" id="myform" onsubmit="return validateForm( );">
Please fill in the fields to add a new member
<p></p>
<input type="text" class="span3" placeholder="Enter member name"name="name" id="name" /><br />
<input type="text" class="span3"placeholder="Enter an address"name="address" id="address" /><br />
<input type="text" class="span3"placeholder="Enter a postcode"name="postcode" id="postcode" /><br />
<input type="text"class="span3" placeholder="Enter a picture (optional)"name="photo" /><br />
<p>
<button class="btn btn-primary" type="submit" value="Save" >Submit </button>
</p>
</form>
Your button doesn't have a name="Submit" attribute. Your php code can't find the $_POST['Submit'] because it doesn't exist.
Consequently, the if (isset($_POST['Submit'])) { condition will return false meaning the validation is never performed and the $error variable never set to a value.

Categories