How do I echo the form input without having to re-display the form after validation? I can only display the input after the form. Here is the code I have
<?php
$postalCode = $_POST['postalCode'];
$postalCodeErr = "";
$postalCodeValidation = '/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/';
$postalCodeIsValid = false;
?>
<html>
<body>
INT322 Lab 3-1
<br />
<br />
<form name="lab3form" action="index.php" method="post">
Postal Code:
<input type="text" name="postalCode" value="<?php if(isset($postalCode)) echo $postalCode; ?>" />
<?php
if(($postalCode != "") && preg_match($postalCodeValidation, $postalCode)) {
$postalCodeIsValid = true;
}
else {
$postalCodeErr = "Invalid Postal Code";
}
if(isset($postalCode)) echo " $postalCodeErr";
?>
<br />
<br />
<input type="submit" name="submit" />
</form>
</body>
</html>
<?php
if($_POST['submit'] && $postalCodeIsValid) {
echo "Postal Code: $postalCode";
}
?>
How about wrapping your form in the else of if($_POST['submit'] && $postalCodeIsValid) { ... } else { ... }
<?php
if($_POST['submit'] && $postalCodeIsValid) {
echo "Postal Code: $postalCode";
}
else {
<form name="lab3form" action="index.php" method="post">
Postal Code:
<input type="text" name="postalCode" value="<?php if(isset($postalCode)) echo $postalCode; ?>" />
<?php
if(($postalCode != "") && preg_match($postalCodeValidation, $postalCode)) {
$postalCodeIsValid = true;
}
else {
$postalCodeErr = "Invalid Postal Code";
}
if(isset($postalCode)) echo " $postalCodeErr";
?>
<br />
<br />
<input type="submit" name="submit" />
</form>
}
?>
UPDATED ANSWER with full code:
<html>
<body>
INT322 Lab 3-1
<br />
<br />
<?php
if(!empty($_POST['submit'])):
$postalCode = $_POST['postalCode'];
if(isValidPostalCode($postalCode)):
echo "Postal Code: $postalCode";
else:
form($postalCode, true);
endif;
else:
form();
endif;
?>
</body>
</html>
<?php
function form($postalCode = null, $hasError = false) { ?>
<form name="lab3form" action="postal.php" method="post">
Postal Code:
<input type="text" name="postalCode" value="<?php if(isset($postalCode)) echo $postalCode; ?>" />
<?php if ($hasError): ?>
<div class="error">Invalid Postal Code</div>
<?php endif; ?>
<br />
<br />
<input type="submit" name="submit" />
</form>
<?php }
function isValidPostalCode($postalCode) {
$postalCodeValidation = '/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/';
return !empty($postalCode) && preg_match($postalCodeValidation, $postalCode);
}
?>
Please note that your regular expression only works with postal codes such as A1B2C3 - I'm not sure if this is the behavior you want.
Related
Here is my code:
<h2> Simple Form </h2>
<form action="" method="post">
First Name: <input type="text" name="firstName">
Last Name: <input type="text" name="lastName"><br /><br />
<input type="submit">
</form>
<br />
Welcome,
<?php
echo $_POST['firstName'];
echo " ";
echo $_POST['lastName'];
?>
!
<hr>
<h2>POST Form</h2>
<h3>Would you like to volunteer for our program?</h3>
<form action="" method="post">
Name: <input type="text" name="postName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
echo $_POST['postName'];
?>
!
<br>
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$age = $_POST['age'];
if ($age >= 16) {
echo "You are old enough to volunteer for our program!";
} else {
echo "Sorry, try again when you're 16 or older.";
}
}
?>
<hr>
<h2>GET Form</h2>
<h3>Would you like to volunteer for our program?</h3>
<form method="get" action="<?php echo htmlspecialchars($_SERVER["REQUEST_URI"]); ?>">
<input type="hidden" name="p" value="includes/forms.php">
Name: <input type="text" name="getName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
echo $_GET['getName'];
?>
!
<br>
<?php
if ($_SERVER['REQUEST_METHOD'] == "GET") {
$age = $_GET['age'];
if ($age >= 16) {
echo "You are old enough to volunteer for our program!";
} else {
echo "Sorry, try again when you're 16 or older.";
}
}
?>
I have two forms. Both displaying the exact same thing, but one form using POST and one using GET.
I have gotten so close to finishing this off but now I have another small/weird issue.
The code technically works correctly, but here's the output explanation:
when I first open up the page the GET form already has the result "Sorry, try again when you're 16 or older." When I fill out the first 'simple' form, it displays the result correctly but then the POST form shows the "Sorry, try again..." result. Then, when I fill in the information and click submit, it displays the correct result and the other two forms are blank as they're supposed to be, and then the same result when I fill out the GET form.
Any help on this is much appreciated.
Try this code :
<h2> Simple Form </h2>
<form action="" method="post">
First Name: <input type="text" name="firstName">
Last Name: <input type="text" name="lastName"><br /><br />
<input type="submit">
</form>
<br />
Welcome,
<?php
if (isset($_POST['firstName']) && $_POST['lastName'])
{
echo $_POST['firstName'];
echo " ";
echo $_POST['lastName'];
}
?>
!
<hr>
<h2>POST Form</h2>
<h3>Would you like to volunteer for our program?</h3>
<form action="" method="post">
Name: <input type="text" name="postName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
if (isset($_POST['postName']))
{
echo $_POST['postName'];
}
?>
!
<br>
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (isset($_POST['age']))
{
$age = $_POST['age'];
if ($age >= 16)
{
echo "You are old enough to volunteer for our program!";
}
else
{
echo "Sorry, try again when you're 16 or older.";
}
}
}
?>
<hr>
<h2>GET Form</h2>
<h3>Would you like to volunteer for our program?</h3>
<form method="get" action="<?php echo htmlspecialchars($_SERVER["REQUEST_URI"]); ?>">
<input type="hidden" name="p" value="includes/forms.php">
Name: <input type="text" name="getName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
if (isset($_GET['getName']))
{
echo $_GET['getName'];
}
?>
!
<br>
<?php
if ($_SERVER['REQUEST_METHOD'] == "GET")
{
if (isset($_GET['age']))
{
$age = $_GET ['age'];
if ($age >= 16)
{
echo "You are old enough to volunteer for our program!";
}
else
{
echo "Sorry, try again when you're 16 or older.";
}
}
}
?>
Please try this. I hope it will help.
Replace
if ($_SERVER['REQUEST_METHOD'] == "POST") {
with
if (isset($_POST['age'])) {
Similarly,Replace
if ($_SERVER['REQUEST_METHOD'] == "GET") {
with
if (isset($_GET['age'])) {
When you first enter on page, default REQUEST_METHOD is GET so you should check if isset($_GET['age']) {
and here check if it is more than 16
}
also you should check this one
echo $_GET['getName']; and change on this
echo isset($_GET['getName']) ? $_GET['name'] : "";
You should also check $_POST request like this and your program will work correctly.
I've been doing a project for php, about sticky keys. It's quite straight forward. However I'm getting a few errors... I'm using CodeLobster.
Can anyone help me find my error on this ?
I've been looking for 2hrs now, I tried the debug, but I don't really know how to use it here.
Thank you so much. Any helps will be appreciated
This is what I am getting:
Output should be this:
<html><head><title>Empty Fields</title>
<body><div align="center">
<h2>Validating Input</h2>
<?php
$errors = array();
if(isset($_POST['submit'])){
validate_input();
if(count($errors) != 0){
display_form();
}
else{
echo "<b>OK! Go ahead and Process the form!</b><br/>";
}
}
else{
display_form();
}
function validate_input(){
global $errors;
if($_POST['name'] == ""){
$errors['name'] = "<font color='red'>***Your name?***</font>";
}
if($_POST['phone'] == ""){
$errors['phone'] = "<font color='red'>***Your phone?</font>";
}
}
function display_form(){
global $errors;
?>
<b>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
What is your name?<br/>
<input type="text" name="name" value="<?php echo $_POST['name']; ?>" /><br/>
<?php echo $errors['name']; ?><br/>
What is your phone number?<br/>
<input type="text" name="phone" value="<?php echo $_POST['phone']; ?>" /><br/>
<?php echo $errors['phone']; ?><br/>
<input type="reset" />
<input type="submit" name="submit" /><br/>
</form></b>
<?php
}
?>
</div>
</body>
</html>
Can you please check once this code:-
<html><head><title>Empty Fields</title>
<body><div align="center">
<h2>Validating Input</h2>
<?php
$errors = array();
if(isset($_POST['submit'])){
validate_input();
if(count($errors) != 0){
display_form();
}
else{
echo "<b>OK! Go ahead and Process the form!</b><br/>";
}
}
else{
display_form();
}
function validate_input(){
global $errors;
if($_POST['name'] == ""){
$errors['name'] = "Your name?";
}
if($_POST['phone'] == ""){
$errors['phone'] = "Your phone?";
}
}
function display_form(){
global $errors;
?>
<b>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
What is your name?<br/>
<input type="text" name="name" value="<?php if(isset($_POST['name'])){echo $_POST['name'];} ?>" /><br/>
<?php if(isset($errors['name'])){echo $errors['name'];} ?><br/>
What is your phone number?<br/>
<input type="text" name="phone" value="<?php if(isset($_POST['name'])){$_POST['phone'];} ?>" /><br/>
<?php if(isset($errors['phone'])){echo $errors['phone'];} ?><br/>
<input type="reset" />
<input type="submit" name="submit" /><br/>
</form></b>
<?php
}
?>
</div>
</body>
</html>
I try to revise your code, There are many point to fixed.
First, you need to keep $_POST['name'] and $_POST['phone'] in variable for easy to use in each function.
Like this,
$name = (isset($_POST['name']) ? $_POST['name'] : '');
$phone = (isset($_POST['phone']) ? $_POST['phone'] : '');
You also need to add code below to first line in function that need to use this variable
global $name;
global $phone;
In function display_form you need to check $errors['name'] and $errors['name'] is empty or not before print(echo) the line.
if (isset($errors['name'])) echo $errors['name'];
if (isset($errors['phone'])) echo $errors['phone'];
So, Finally the code should be like the below, I tried this code without error.
<html>
<head><title>Empty Fields</title>
<body>
<div align="center">
<h2>Validating Input</h2>
<?php
$errors = array();
$name = (isset($_POST['name']) ? $_POST['name'] : '');
$phone = (isset($_POST['phone']) ? $_POST['phone'] : '');
if(isset($_POST['submit']))
{
validate_input();
if(count($errors) != 0)
{
display_form();
}
else
{
echo "<b>OK! Go ahead and Process the form!</b><br/>";
}
}
else
{
display_form();
}
function validate_input(){
global $errors;
global $name;
global $phone;
if($name == '')
{
$errors['name'] = "<font color='red'>***Your name?***</font>";
}
if($phone == '')
{
$errors['phone'] = "<font color='red'>***Your phone?</font>";
}
}
function display_form(){
global $errors;
global $name;
global $phone;
?>
<b>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
What is your name?<br/>
<input type="text" name="name" value="<?php echo $name; ?>" /><br/>
<?php if (isset($errors['name'])) echo $errors['name']; ?><br/>
What is your phone number?<br/>
<input type="text" name="phone" value="<?php echo $phone; ?>" /><br/>
<?php if (isset($errors['phone'])) echo $errors['phone']; ?><br/>
<input type="reset" />
<input type="submit" name="submit" /><br/>
</form></b>
<?php
}
?>
</div>
</body>
</html>
Simply use isset($var); to avoid Undefined index: EROOR on php.
echo isset($_POST['name']);
echo isset($_POST['phone']);
wherever you need.
member.php
<?php
if(isset($_POST['submit']))
{
$membername = $_POST['membername'];
if(empty($membername))
{
$errors .= "Please enter member name<br />";
}
if($errors)
{
$action = $_POST['submit'];
echo $errors;
displayForm();
}
else
{
?>
<input type="hidden" name="mname" value="<?php echo $_POST['membername']; ?>" />
<?php
$action = $_POST['submit'];
header("Location: commit.php?action=$action");
exit();
}
}
else
{
displayForm();
}
?>
<?php
function displayForm()
{
?>
<form action = "member.php" action="post">
Member Name <input type="text" name="membername" value="<?php if(isset($row['name'])) echo $row['name'];
else echo ''; ?>" /><br /><input type="text" name="membername" value=
<input type="submit" name="submit" name="add" />
</form>
<?php
}
?>
Commit.php
<?php
echo $_POST['mname']; //HERE
?>
I want to pass the hidden value from member.php. When I run commmit.php, I want to get hidden field value. However, the error is the following:
**Undefined index: mname in member.php in commit.php.
What am I doing wrong?
Here is the html and Php code i have used:
<?php
require_once('include_function.php');
require_once('validation_functions.php');
$errors = array();
$message ="";
if(isset($_POST['submit'])){
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if (array_key_exists('submit', $_POST)){
}
$fields_required = array("username","password");
foreach($fields_required as $field){
$value = trim($_POST[$field]);
if(!has_presence($value)){
$errors[$field]= ucfirst($field). " Cant Be blank";
}
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Single page Submission</title>
</head>
<body>
<?php echo $message;?>
<?php echo form_error($errors)?>
<form action="form_with_validation.php" method="post">
Username<input type="text" name="username" value=""/><br/>
Password<input type="password" value="" name="password" /><br/>
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
And these are functions I have used
function has_presence($value){
return isset($value) && $value !=="";
}
function form_error($errors=array()){
$output = "";
if(!empty($errors)){
$output .="<div class=\"error\">";
$output .="Please fix the following errors";
$output .="<ul>";
foreach($errors as $key => $field){
$output .= "<li>{$field}</li>";
}
$output .="</ul>";
$output .="</div>";
}
return $output;
}
Can someone please guide me to validate the form using if array key exists
So that I get error message next to Or below the input field
or any other method which does the needful
<?php
$errors = array();
$message ="";
if(isset($_POST['submited'])){
$fields_required = array("username","password");
foreach($fields_required as $field)
if (!isset($_POST[$field]) || $_POST[$field]=="")
$errors[$field]= $field. " Cant Be blank";
}
function form_error($errors=array()){
$output = "";
if(!empty($errors)) {
$output .="<div class=\"error\">";
$output .="Please fix the following errors";
$output .="<ul>";
foreach($errors as $key => $field){
$output .= "<li>{$field}</li>";
}
$output .="</ul>";
$output .="</div>";
}
return $output;
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Single page Submission</title>
</head>
<body>
<?php echo $message;?>
<form action="form_with_validation.php" method="post">
<input type="hidden" name="submited" value="1" />
Username<input type="text" name="username" value=""/><br/>
Password<input type="password" value="" name="password" /><br/>
<input type="submit" name="submit" value="Submit" />
</form>
<?php echo form_error($errors)?>
</body>
</html>
#sandeep S K Can you please try once below code? :
Note: Please include your required DB connection or validation files on the top of the script.
<?php
function has_presence($value){
return isset($value) && $value !=="";
}
function form_error($errors=array()){
$output = "";
if(!empty($errors)){
$output .="<div class=\"error\">";
$output .="Please fix the following errors";
$output .="<ul>";
foreach($errors as $key => $field){
$output .= "<li>{$field}</li>";
}
$output .="</ul>";
$output .="</div>";
}
return $output;
}
$errors = array();
$message ="";
if(isset($_POST['submit'])){
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if (array_key_exists('submit', $_POST)){
}
$fields_required = array("username","password");
foreach($fields_required as $field){
$value = trim($_POST[$field]);
if(!has_presence($value)){
$errors[$field]= ucfirst($field). " Cant Be blank";
}
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Single page Submission</title>
</head>
<body>
<?php echo $message;?>
<?php if(!empty($errors)) { ?>
<div class="has_errors">
<ul>
<li>
There are errors in your input. Please fix them and try again.
</li>
</ul>
</div>
<?php
}
?>
<form action="index.php" method="post">
Username<input type="text" name="username" value=""/>
<?php
if (array_key_exists('username', $errors)) {
?>
<div class="has_errors">
<ul>
<li>
<?php print $errors['username'];?>
</li>
</ul>
</div>
<?php
}
?>
<br/>
Password<input type="password" value="" name="password" />
<?php
if (array_key_exists('password', $errors)) { ?>
<div class="has_errors">
<ul>
<li>
<?php print $errors['password'];?>
</li>
</ul>
</div>
<?php
}
?>
<br/>
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Ok, I have a script called profile.php and I would like the user to interact with profile.php "form input" from a different html page or php script such as user_settings.php.
I would like to have the errors ONLY from profile.php to be displayed/echoed/printed on user_settings.php page. I have tried the following
----profile.php---
<?php ob_start(); require_once ("core/init.php"); ?>
<?php require ("includes/overall/header.php"); ?>
<?php
if(has_access($session_user_id, 1) === true){
$message[] = '<p class="admin"> **Admin**</p>';
}
?>
<div id="mainInfo">
<p class="profile"> Hello <?php echo $user_data['first_name'], '!' .output_message($message) ;?> </p><br /><br />
<?php
if(isset($_FILES['image']) === true)
{
if(empty($_FILES['image']['name']) === true)
{
$errors_image[] = 'Please choose a file';
}
else
{
$allowed = array('jpg', 'jpeg', 'gif', 'png');
$file_name = $_FILES['image']['name'];
$file_extn = strtolower(end(explode('.', $file_name)));
$file_temp = $_FILES['image']['tmp_name'];
if(in_array($file_extn, $allowed) === true)
{
change_profile_image($session_user_id, $file_temp, $file_extn);
header('Location: profile');
exit();
}
else
{
$errors_image[] = 'Incorrect file type. Allow: ';
echo implode(', ', $allowed);
}
}
}
if(empty($user_data['image']) === false)
{
echo '<p class="photo"><image src="', $user_data['image'],'" alt="', $user_data['first_name'], '\'s Profile Image"></p> <br>';
}
?>
<p class="usr_sttngs"> Update Info!</p><br />
</div>
<?php require ("includes/overall/footer.php"); ?>
--------usr_sttngs.php------------
<?php ob_start();
require_once ("core/init.php");
ini_set('display_errors', 'On'); error_reporting(E_ALL);
protect_page(); ?>
<?php
if(empty($_POST) === false)
{
$required_fields = array('current_passwd','passwd', 'passwd_again');
foreach($_POST as $key => $value)
{
if (empty($value) && in_array($key, $required_fields) === true)
{
$errors[] = '<p class="postad_msg">Fields marked with * are required.</p>';
break 1;
}
}
if (sha1($_POST['current_passwd']) === $user_data['passwd'])
{
if(trim($_POST['passwd']) !== trim($_POST['passwd_again']))
{
$errors[] = '<p class="postad_msg">New passwords DO NOT match!</p>';
}
else if (strlen($_POST['passwd']) < 6)
{
$errors[] = '<p class="postad_msg">New passwords must be at least 6 characters.</p>';
}
}
else
{
$errors[] = '<p class="postad_msg">Your current password is incorrect!</p>';
}
}
?>
<?php require ("includes/overall/header.php"); ?>
<div id="mainInfo">
<br /> <br /><p3>Change Password!</p3> <br /> <br />
<?php
if(isset($_GET['success']) && empty($_GET['success']))
{
$message[] = '<p class="postad_msg">Your password has been changed successfully.</p>';
}
if(empty($_POST) === false && empty($errors) === true)
{
change_passwd($session_user_id, $_POST['passwd'] );
//redirect
header('Location: usr_sttngs?success');
//exit
exit();
}
else if(empty($errors) === false)
{
output_errors($errors);
}
?>
<form method="post" action="usr_sttngs">
<fieldset>
<label for="currentpasswd">Current password* </label>
<input placeholder="Type your current password" type="password" name="current_passwd" size="30" maxlength="50" value="<?php echo htmlentities($current_passwd); ?>" /><br /><br />
<label for="last_name">New Password* </label>
<input placeholder="New Password" type="password" name="passwd" size="30" maxlength="50" value="<?php echo htmlentities($new_passwd); ?>" /><br /><br />
<label for="email">New Password Again* </label>
<input placeholder="Retype New Password" type="password" name="passwd_again" size="30" maxlength="50" value="<?php echo htmlentities($new_passwd_again); ?>" />
</fieldset>
<fieldset class="center">
<input class="submit" type="submit" name="submit" value="Change Password" />
<?php echo output_errors($errors); ?>
<?php echo output_message($message);?>
</fieldset>
</form>
<p4>Change profile photo!</p4> <br /> <br />
<form action="profile" method="post" enctype="multipart/form-data">
<fieldset class="center">
<input type="file" name="image"> <input type="submit">
<?php echo output_errors($errors_image);
require_once ('$_SERVER["DOCUMENT_ROOT"]\profile.php');
?>
</fieldset>
</form>
<br /><br /><br /><p4>Upload your resume!</p4> <br />
<form action="profile" method="post" enctype="multipart/form-data">
<fieldset class="center">
<input type="file" name="resume"> <input type="submit">
</fieldset>
</form>
</div>
<?php require ("includes/overall/footer.php"); ?>
I tried something I read on the following post Want to echo a php variable from another page but I did not get the desired results. So I tried to include the required_once 'profile.php' ; at the very top of the user_setting.php file and that just gives me a blank page. Any help would be greatly appreciated. Thank you!
Require or Require_once must be called before any HTML is displayed.
Try placing your require_once at the beginning of the file.
EDITED
Try the following test code to see if you can get it working.
The profile.php should contain the following:
<?php
echo "profile.php is displaying correctly";
?>
The user_settings.php should contain the following:
<?php
require_once("profile.php");
?>
See if you can get this basic code to work. Post your results
I get the bellow page when I try the code above: