Why is htmlentities not working in my Autosdb code? - php

All I am trying to do is escape html injection into my input text boxes. Am I not using htmlentities correctly?
Code:
<?php
require_once "pdo.php";
// Demand a GET parameter
if ( ! isset($_GET['name']) || strlen($_GET['name']) < 1 ) {
die('Name parameter missing');
} else {
$username = $_GET['name'];
}
// If the user requested logout go back to index.php
if ( isset($_POST['logout']) ) {
header('Location: index.php');
return;
}
$year = isset($_POST['year']) ? $_POST['year'] : '';
$mileage = isset($_POST['mileage']) ? $_POST['mileage'] : '';
$make = isset($_POST['make']) ? $_POST['make'] : '';
$failure = false;
$success = false;
if ( isset($_POST['make']) && isset($_POST['year'])
&& isset($_POST['mileage'])) {
//$year = $_POST['year'];
//$mileage = $_POST['mileage'];
//$make = $_POST['make'];
if ( strlen($make) < 1){
$failure = "Make is Required";
} else {
if (is_numeric($year) and is_numeric($mileage) ){
error_log("year is a number ".$_POST['year']);
error_log("Mileage is a number ".$_POST['mileage']);
$sql = "INSERT INTO autos (make, year, mileage)
VALUES (:make, :year, :mileage)";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':make' => $make,
':year' => $year,
':mileage' => $mileage));
$success = "Record Inserted";
} else {
$failure = "Mileage and Year must be numeric";
error_log("year or mileage is not a number year=".$_POST['year']);
error_log("Mileage or year is not a number mileage=".$_POST['mileage']);
}
}
}
if ( isset($_POST['delete']) && isset($_POST['auto_id']) ) {
$sql = "DELETE FROM autos WHERE auto_id = :zip";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':zip' => $_POST['auto_id']));
}
$stmt = $pdo->query("SELECT make, year, mileage, auto_id FROM autos");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<title>Douglas Osborne's Automobile Tracker</title>
</head>
<body>
<table border="0">
<?php
foreach ( $rows as $row ) {
echo "<tr><td>";
echo($row['year']);
echo(" /");
echo("</td><td>");
echo($row['make']);
echo("</td><td>");
echo($row['mileage']);
echo(" miles");
echo("</td><td>");
echo('<form method="post"><input type="hidden" ');
echo('name="auto_id" value="'.$row['auto_id'].'">'."\n");
echo('<input type="submit" value="Del" name="delete">');
echo("\n</form>\n");
echo("</td></tr>\n");
}
?>
<body>
<div class="container">
<h1>
<?php
if ( isset($_REQUEST['name']) ) {
echo "<p>Tracking Autos for ";
echo htmlentities($_REQUEST['name']);
echo "</p>\n";
}
?>
</h1>
<p>
<?php
// Note triple not equals and think how badly double
// not equals would work here...
if ( $failure !== false ) {
// Look closely at the use of single and double quotes
echo('<p style="color: red;">'.htmlentities($failure)."</p>\n");
}
if ( $success !== false ) {
// Look closely at the use of single and double quotes
echo('<p style="color: green;">'.htmlentities($success)."</p>\n");
}
?>
</p>
<form method="post">
<p>Make:
<input type="text" name="make" size="60" value="<?= htmlentities($make) ?>"/>
</p>
<p>Year:
<input type="text" name="year" value="<?= htmlentities($year) ?>"/>
</p>
<p>Mileage:
<input type="text" name="mileage" value="<?= htmlentities($mileage) ?>"/>
</p>
<input type="submit" value="Add">
<input type="submit" name="logout" value="Logout">
</form>
<h2>Automobiles</h2>
<ul>
<p>
</ul>
</div>
</html>
Output wont escape see screenshot:

Adding htmlspecialchars to (make) gave me the result I was looking for. Thanks for anyone's attempt to help me.

Related

PHP sending form accorded to a url token

i'm learning php since a week from now, and one of my project is to make a form that adapt fields about a url token.
For example: if the user is a student token will be index.php?token=e3
the user is a professionnal will be index.php?token=p4
i'm realy happy because everything is working, except the last part.. the POST of the user informations in my db called "test" which as a single table called form and i the db got good settings, the table is well designed with int-varchars, anything that can handle the datas.
i would like to atleast make it work for e3 then i'll be able to adapt for the others, that's why i give you an example of what i did since now, maybe i'm missing something important but i got no php errors, the datas are not sending when i press send button and the page refresh as index.php
if you guys got an idea, you don't need to tell me realy how to do, i just need someone better than me that could tell me "well you should look at sessions" or something else that is wrong because i have no clue to debug i'm stuck since yesterday on this problem.
Here is my code remember if you want to make it appear clearly you need to specify the token "?token=e3"
thank you in advance everyone who'll help me:
<?php
session_start();
$connectionSql = array(
"hote" => "localhost",
"base" => "test",
"user" => "root",
"pwd" => "",
);
try {
$db = new PDO("mysql:host=" . $connectionSql["hote"] . ";dbname=" . $connectionSql["base"],
$connectionSql["user"], $connectionSql["pwd"]);
/*var_dump($db);*/
$db->exec("set names utf8");
} catch (PDOException $e) {
echo $e->getMessage();
die();
}
$getWholeUrl = "http://".$_SERVER['HTTP_HOST']."".$_SERVER['REQUEST_URI']."";
$url = substr($getWholeUrl , -2);
if ($url=="e3" && isset($_POST['send'])) {
if(!empty($_POST['gender']) AND !empty($_POST['name']) AND
!empty($_POST['firstname']) AND !empty($_POST['mail']) AND
!empty($_POST['phone']) AND !empty($_POST['speciality']) AND
$_POST['speciality'] != "Votre spécialité" AND !empty($_POST['year']) AND
!empty($_POST['birthday']) AND !empty($_POST['school']) AND
!empty($_POST['zipcode']) AND !empty($_FILES['attachment']) AND
!empty($_FILES['pi']))
{
$gender = $_POST['gender'];
$name = htmlspecialchars($_POST['name']);
$firstname = htmlspecialchars($_POST['firstname']);
$mail = htmlspecialchars($_POST['mail']);
$phone = $_POST['phone'];
$speciality = $_POST['speciality'];
$year = $_POST['year'];
$birthday = $_POST['birthday'];
$school = htmlspecialchars($_POST['school']);
$zipcode = htmlspecialchars($_POST['zipcode']);
$filename = $_FILES['attachment']['name'];
$idname = $_FILES['pi']['name'];
$reqmail= $db->prepare("SELECT * FROM `form` WHERE mail = ?");
$reqmail->execute(array($mail));
$mailexist = $reqmail->rowCount();
if($mailexist == 0) {
if (filter_var($mail, FILTER_VALIDATE_mail)) {
if (is_numeric($phone) == true && preg_match('/^\d{10}$/', $phone)) {
if (is_numeric($year) == true) {
if(!empty($_FILES['attachment']['name']) && !empty($_FILES['pi']['name'])){
if ($_FILES['attachment']['error'] == 0 && $_FILES['attachment']['size'] < 2097152 && $_FILES['pi']['error'] == 0 && $_FILES['pi']['size'] < 2097152) {
$extension = pathinfo($filename);
if ($extension["extension"] == "jpg" || $extension["extension"] == "png" || $extension["extension"] == "pdf") {
$extensionid = pathinfo($idname);
if($extensionid["extension"] == 'jpg' || $extensionid['extension'] == "png" || $extensionid['extension'] == "pdf") {
$req = $db->query('SELECT MAX(id) FROM form');
$res = $req->fetchColumn();
$res += 1;
if(!is_dir('img/')) {
mkdir('img/', 0755);
}
if(!is_dir('img/img' . $res . '/')){
mkdir('img/img' . $res . '/', 0755);
}
move_uploaded_file($_FILES['attachment']['tmp_name'], 'img/img' . $res . '/' . $res . $filename);
move_uploaded_file($_FILES['pi']['tmp_name'], 'img/img' . $res . '/' . $res . 'id' . $idname);
$require = $db->prepare("INSERT INTO `form` (`gender`, `name`, `firstname`, `mail`, `phone`, `speciality`, `year`, `birthday`, `school`, `zipcode`, `attachment`, `idcard`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$require->execute(array($gender, $name, $firstname, $mail, $phone, $speciality, $year, $birthday, $school, $zipcode, $res . $filename, $res . $idname));
$succes = "Form as been sent !";
}else{
$erreur = "idcard's extension isn't admitted.";
}
}else{
$erreur = "attachment's extension isn't admitted.";
}
}else{
$erreur = "File too big - Max 2Mo";
}
}else{
$erreur = "Please join the two required attached files.";
}
} else {
$erreur = $year . " isn't a valable year !";
}
} else {
$erreur = $phone . " isn't a right phone number !";
}
}else{
$erreur = "invalid mail";
}
}else{
$erreur = "mail already exists !";
}
}else{
$erreur = "please complete all the fields !";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form</title>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<link rel="icon" type="image/icon-x" href="images/favicon.ico">
</head>
<body>
<div class="background">
<div align="center">
<h1 class="logo">
<img src="images/logo.png" alt="logo">
</h1>
<?php
if(isset($succes))
{
echo "<div class=\"alert alert-success\">".$succes."</div>";
}
if(isset($erreur))
{
echo "<div class=\"alert alert-danger\">".$erreur."</div>";
}
?>
<div class="image">
<section>
<form method="post" action="index.php" enctype="multipart/form-data">
<div class="radioclass">
<input type="radio" name="gender" id="gender" value="1"/>
<label class="btn" for="gender">Woman</label>
<input type="radio" name="gender" id="gender" value="2"/>
<label class="btn" for="gender">Man</label>
<input type="radio" name="gender" id="gender" value="3"/>
<label class="btn" for="gender">Unicorn</label>
</div>
<div class="user-input-wrp">
<div class="user-input-name">
<input type="text" name="name" id="name"/ required>
<span class="name">name</span>
</div>
<div class="user-input-surname">
<input type="text" name="firstname" id="firstname"/ required>
<span class="firstname">firstname</span>
</div>
<div class="user-input-mail">
<input type="mail" name="mail" id="mail"/ required>
<span class="mail">mail</span>
</div>
<div class="user-input-mobile">
<input type="tel" name="phone" id="phone" required>
<span class="phone">phone</span>
</div>
<?php
$getWholeUrl = "http://".$_SERVER['HTTP_HOST']."".$_SERVER['REQUEST_URI']."";
if(substr($getWholeUrl , -2)=='e3'){
$listespeciality = array("your speciality",
"Fitness",
"Bodybuilding",
"Flower-eating");
echo "<select name=\"speciality\" id=\"speciality\">";
foreach ($listespeciality as $indice => $speciality) {
echo "<option value=\"";
echo $speciality;
echo "\">";
echo $speciality;
echo "</option>";
}
echo "</select>";
}
else {
echo "<div class=\"user-input-seccia\">"."<input type=\"text\" name=\"secteur\" id=\"secteur\">"."<span class=\"secteur\">activity</span>"."</div>";
}
?>
<div class="user-input-year">
<input type="text" name="year" id="year" required>
<span class="year">Year of activity</span>
</div>
<?php
$getWholeUrl = "http://".$_SERVER['HTTP_HOST']."".$_SERVER['REQUEST_URI']."";
if(substr($getWholeUrl , -2)=='e3'){
echo "
<div class=\"user-input-building\">
<input type=\"text\" name=\"school\" id=\"school\" required>
<span class=\"school\">school</span>
</div>";}
else if(substr($getWholeUrl , -2)=='p4' || substr($getWholeUrl , -2)=='o1') {
echo "
<div class=\"user-input-siret\">
<input maxlength=\"14\" type=\"text\" name=\"idcode\" id=\"idcode\" required>
<span class=\"siret\">identity code</span>
</div>";} ?>
<?php
$getWholeUrl = "http://".$_SERVER['HTTP_HOST']."".$_SERVER['REQUEST_URI']."";
if(substr($getWholeUrl , -2)=='a2') {
$listmedia = array("Blog",
"Facebook",
"Instagram",
"Own website");
echo "<select name=\"media\" id=\"media\">";
foreach ($listmedia as $indice => $media) {
echo "<option value=\"";
echo $media;
echo "\">";
echo $media;
echo "</option>";
}
echo "</select>";
} ?>
<?php $getWholeUrl = "http://".$_SERVER['HTTP_HOST']."".$_SERVER['REQUEST_URI']."";
if(substr($getWholeUrl , -2)=='o1' || substr($getWholeUrl , -2)=='p4'){
echo "
<div class=\"user-input-company\">
<input type=\"text\" name=\"company\" id=\"company\" required/>
<span class=\"company\">company</span>
</div>";}
else if (substr($getWholeUrl , -2)=='a2') {
echo "
<div class=\"user-input-url\">
<input type=\"text\" name=\"url\" id=\"url\" required/>
<span class=\"url\">Link of media</span>
</div>";}
else if (substr($getWholeUrl , -2)=='e3'){
echo "
<div class=\"user-input-zipcode\">
<input type=\"text\" name=\"zipcode\" id=\"zipcode\" required/>
<span class=\"zipcode\">Zipcode</span>
</div>"
;}?>
<?php if (substr($getWholeUrl , -2)=='e3' || substr($getWholeUrl , -2)=='a2' || substr($getWholeUrl , -2)=='p4'){
echo "
<input type=\"Date\" name=\"birthday\" id=\"birthday\" min=\"1930-01-01\" max=\"2020-12-29\" value=\"2000-01-01\">
<span class=\"birthday\">birthday</span>
";}
else echo "<br><br><br><br><br>"
?>
<?php if (substr($getWholeUrl , -2)=='e3') {
echo "
<div class=\"user-input-attachment\">
<div>"; if(isset($error)) echo $error; echo "</p></div>
<input type=\"file\" name=\"attachment\" id=\"attachment\" value=\"\"/>
<span class=\"attachment\">attachment:</span>
</div>"; }
else if (substr($getWholeUrl , -2)=='p4' || substr($getWholeUrl , -2)=='a2') { echo "<br><br><br><br><br><br>";}
else if (substr($getWholeUrl , -2)=='o1') { echo "<br><br><br><br><br>";}
?>
<div class="user-input-idcard">
<div><p><?php if(isset($error)) echo $error;?></p></div>
<input type="file" name="pi" id="pi" value=""/>
<span class="idcard">identity card :</span>
</div>
<input type="submit" id="send" name="send" value="Send"/>
</div>
</form>
</section>
</div>
</div>
</div>
</body>
</html>

I'm trying to display errors when the form field are empty or not numeric values and stop the form from submitting when empty , What I'm doing wrong?

<?php
require_once "pdo.php";
$failure = false;
// Demand a POST parameter
if (isset($_POST['make']) && isset($_POST['year']) && isset($_POST['mileage'])) {
// if (empty($_POSt['make']) && empty($_POST['year']) && empty($_POST['mileage'])) {
// $failure = "Mileage and year must be numeric";
// return false;
// }
$sql = "INSERT INTO autos (make, year, mileage) VALUES (:mk, :yr, :mi)";
$stmt = $pdo->prepare($sql);
$stmt -> execute(array(
':mk' => $_POST['make'],
':yr' => $_POST['year'],
':mi' => $_POST['mileage']));
// $row = $stmt->fetch(PDO::FETCH_ASSOC);
$make = $_POST['make'];
$year = $_POST['year'];
$mileage = $_POST['mileage'];
if (empty($_POST['make'])) {
$_SESSION['make'] = $failure = "Make is required";
}else {
if(!empty($_POST['make']) && is_numeric($_POST['year']) && is_numeric($_POST['mileage'])){
echo '<p style="color: green">Record inserted'."</p>\n";
}else {
if(is_numeric($_POST['year']) === false && is_numeric($_POST['mileage']) === false){
$failure = "Mileage and year must be numeric";
header("Location: autos.php?name=".urlencode($_POST['who']));
return false;
}
}
}
}
// If the user requested logout go back to index.php
if ( isset($_POST['logout']) ) {
header('Location: index.php');
return;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Automobile Tracker</title>
<?php require_once "bootstrap.php"; ?>
</head>
<body>
<div class="container">
<!-- <h1>Tracking Autos for </h1> -->
<?php
if ( isset($_REQUEST['name']) ) {
echo "<h1>Tracking Autos for ";
echo htmlentities($_REQUEST['name']);
echo "</a></h1>\n";
}
if(!empty($_POST['make']) && is_numeric($_POST['year']) && is_numeric($_POST['mileage'])){
echo '<p style="color: green">Record inserted'."</p>\n";
}
if ( $failure !== false ) {
// Look closely at the use of single and double quotes
echo('<p style="color: red;">'.htmlentities($failure)."</p>\n");
}
?>
<form method="post">
<p>Make:
<input type="text" name="make" size="60"/></p>
<p>Year:
<input type="text" name="year"/></p>
<p>Mileage:
<input type="text" name="mileage"/></p>
<input type="submit" value="Add">
<input type="submit" name="logout" value="Logout">
</form>
<h2>Automobiles</h2>
<ul>
<?php
$stmt = $pdo->query("SELECT make, year, mileage FROM autos");
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<li>";
echo($row['year']);
echo " ";
echo($row['make']);
echo " / ";
echo($row['mileage']);
echo "</li>";
}
?>
</ul>
</div>
</body>
</html>
So far if I'm trying to submit the form with empty field i get the error "Make is required", but it's still submitting the form , and also If i add something into make field and nothing in year and mileage field i don't get the error "Mileage and year must be numeric" even if i add something that is not numeric i don't get the error for them.
Please let me know what i did wrog (I just started learning PHP).
Thank you in advance.
It would seem that you're submitting the form input with $stmt -> execute(...) before you validate it. If you want to execute the entry only if the form input is valid, you could e.g. use the boolean $failure and change its value to true if the input doesn't pass your validating if-statements and execute the prepared SQL-statement only if $failure is false at the end of your validation.

How do i verify query record with form input

In my code below i have two form section first one is to fetch information from database and second one is verify a record in the database my problem is how do verify a record and redirect to error page or if the input form do not march any record redirect to index page this my code;
<?php
include_once 'init.php';
$error = false;
//check if form is submitted
if (isset($_POST['book'])) {
$book = mysqli_real_escape_string($conn, $_POST['book']);
$action = mysqli_real_escape_string($conn, $_POST['action']);
if (strlen($book) < 6) {
$error = true;
$book_error = "booking code must be alist 6 in digit";
}
if (!is_numeric($book)) {
$error = true;
$book_error = "Incorrect booking code";
}
if (empty($_POST["action"])) {
$error = true;
$action_error = "pick your action and try again";
}
if (!$error) {
if(preg_match('/(check)/i', $action)) {
echo "6mameja";
}
if (preg_match('/(comfirm)/i', $action)) {
if(isset($_SESSION["user_name"]) && (trim($_SESSION["user_name"]) != "")) {
$username=$_SESSION["user_name"];
$result=mysqli_query($conn,"select * from users where username='$username'");
}
if ($row = mysqli_fetch_array($result)) {
$id = $row["id"];
$username=$row["username"];
$idd = $row["id"];
$username = $row["username"];
$ip = $row["ip"];
$ban = $row["validated"];
$balance = $row["balance"];
$sql = "SELECT `item_name` , `quantity` FROM `books` WHERE `book`='$book'";
$query = mysqli_query($conn, $sql);
while ($rows = mysqli_fetch_assoc($query)) {
$da = $rows["item_name"]; $qty = $rows["quantity"];
$sqll = mysqli_query($conn, "SELECT * FROM promo WHERE code='$da' LIMIT 1");
while ($prow = mysqli_fetch_array($sqll)) {
$pid = $prow["id"];
$price = $prow["price"];
$count = 0;
$count = $qty * $price;
$show = $count + $show;
}
}
echo "$show";
echo "$balance";
if ($show<$balance) {
if (isset($_POST["verify"])) {
$pass = mysqli_real_escape_string($conn, $_POST["pass"]);
if ($pass != "$username") {
header("location: index.php");
}
elseif ($pass = "$username") {
header("location: ../error.php");
}
}
echo '<form action="#" method="post" name="verify"><input class="text" name="pass" type="password" size="25" /><input class="text" type="submit" name="verify" value="view"></form>';
echo "you cant buy here";
exit();
}
} else {
$errormsg = "Error in registering...Please try again later!";
}
}
}
}
?>
<form role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="booking">
<fieldset>
<legend>Check Booking</legend>
<div class="form-group">
<label for="name">Username</label>
<input type="text" name="book" placeholder="Enter Username" required value="<?php if($error) echo $book; ?>" class="form-control" />
<span class="text-danger"><?php if (isset($book_error)) echo $book_error; ?></span>
</div>
<input type="submit" name="booking" value="Sign Up" class="btn btn-primary" />
<table>
<input type="radio" name="action" value="comfirm" <?php if(isset($_POST['action']) && $_POST['action']=="comfirm") { ?>checked<?php } ?>>
<input type="radio" name="action" value="check" <?php if(isset($_POST['action']) && $_POST['action']=="check") { ?>checked<?php } ?>> Check booking <span class="text-danger"><?php if (isset($action_error)) echo $action_error; ?></span>
</div>
</table>
</fieldset>
</form>
in achievement am expected to redirect to error or index page but my code above refress back to first form what are my doing wrong. Big thanks in advance

php form 2 step confirmation

i try to challenge my self but i stuck(
I try to create a php form with 2 steps confirmation:
When the user fill up the form and hit Submit, it checks all the conditions(name, pass etc.). If everything ok automatically redirecting the user.
After redirecting (to the same page) the user can check all the details again.
If they ok, hit again the submit button which redirects to the final page.
I stuck on the 2nd phase...how to redirect to the final page?
I'm very beginner so i'm curios what could be done better or any advise.
<?php
// the php code
session_start();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// setting up the variables
$title = $_POST['title'];
$fName = trim(filter_input(INPUT_POST,'fName', FILTER_SANITIZE_STRING));
$lName = trim(filter_input(INPUT_POST,'lName',FILTER_SANITIZE_STRING));
$age = intval($_POST['age']);
$_SESSION['title'] = $title;
$_SESSION['fName'] = $fName;
$_SESSION['lName'] = $lName;
$_SESSION['age'] = $age;
//checking for possible errors
if ( $fName == "" || strlen($fName) <= 2 ) {
$errorMsg1 = "<span>Provide your First name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $lName == "" || strlen($lName) <= 2 ) {
$errorMsg2 = "<span>Provide your Last name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $age < 18 ) {
$errorMsg3 = "<span>You must be 18 or above!</span>";
$status = false;
}
else { $status = true; }
// redirecting to done page
if ($status) {
header("Location:TEST ZONE.php?status=awaiting");
}
}
?>
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<div id="wrapper">
<?php
if ( isset($_GET['status']) && $_GET['status'] == "awaiting" ) {
echo "<form>"
. "Check your Details!<br>"
. $_SESSION['title'] . "<br>"
. $_SESSION['fName'] . "<br>"
. $_SESSION['lName'] . "<br>"
. $_SESSION['age'] . "<br>"
// **NOW WHEN I'M in the awaiting phase, i don't know what to do(**
. "<input type='submit' name='submit'/>";
echo "</form>";
}
else { ?>
<form action="TEST ZONE.php" method="post">
<h3>Register Form </h3>
<label for="title">Title </label>
<select name="title">
<option name="mr">Mr</option>
<option name="ms">Ms</option>
</select><br><br><br>
<label for="fName">First Name</label><br>
<input type="text" name="fName" id="fName" value="<?php if (isset($fName)) { echo $fName; } ?>"><br><?php
if (isset( $errorMsg1 )) {
echo $errorMsg1;
}
?><br><br>
<label for="lName">Last Name</label><br>
<input type="text" name="lName" id="lName" value="<?php if (isset($lName)) { echo $lName; } ?>"><br><?php
if (isset( $errorMsg2 )) {
echo $errorMsg2;
}
?><br><br>
<label for="age">Age</label><br>
<input type="text" name="age" id="age" value="<?php if (isset($age)) { echo $age; }?>"><br><?php
if (isset($errorMsg3)){
echo $errorMsg3;
} ?><br><br>
<input type="submit" value="Submit"><input type="reset">
</form> <?php } ?>
</div>
</body>
</html>
Add action in your form to redirect final page.
You already have all values in session so you can access it in final page also
<?php
// the php code
session_start();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// setting up the variables
$title = $_POST['title'];
$fName = trim(filter_input(INPUT_POST,'fName', FILTER_SANITIZE_STRING));
$lName = trim(filter_input(INPUT_POST,'lName',FILTER_SANITIZE_STRING));
$age = intval($_POST['age']);
$_SESSION['title'] = $title;
$_SESSION['fName'] = $fName;
$_SESSION['lName'] = $lName;
$_SESSION['age'] = $age;
//checking for possible errors
if ( $fName == "" || strlen($fName) <= 2 ) {
$errorMsg1 = "<span>Provide your First name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $lName == "" || strlen($lName) <= 2 ) {
$errorMsg2 = "<span>Provide your Last name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $age < 18 ) {
$errorMsg3 = "<span>You must be 18 or above!</span>";
$status = false;
}
else { $status = true; }
// redirecting to done page
if ($status) {
header("Location:TEST ZONE.php?status=awaiting");
}
}
?>
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<div id="wrapper">
<?php
if ( isset($_GET['status']) && $_GET['status'] == "awaiting" ) {
echo "<form action='final_page.php'>"
. "Check your Details!<br>"
. $_SESSION['title'] . "<br>"
. $_SESSION['fName'] . "<br>"
. $_SESSION['lName'] . "<br>"
. $_SESSION['age'] . "<br>"
// **NOW WHEN I'M in the awaiting phase, i don't know what to do(**
. "<input type='submit' name='submit'/>";
echo "</form>";
}
else { ?>
<form action="TEST ZONE.php" method="post">
<h3>Register Form </h3>
<label for="title">Title </label>
<select name="title">
<option name="mr">Mr</option>
<option name="ms">Ms</option>
</select><br><br><br>
<label for="fName">First Name</label><br>
<input type="text" name="fName" id="fName" value="<?php if (isset($fName)) { echo $fName; } ?>"><br><?php
if (isset( $errorMsg1 )) {
echo $errorMsg1;
}
?><br><br>
<label for="lName">Last Name</label><br>
<input type="text" name="lName" id="lName" value="<?php if (isset($lName)) { echo $lName; } ?>"><br><?php
if (isset( $errorMsg2 )) {
echo $errorMsg2;
}
?><br><br>
<label for="age">Age</label><br>
<input type="text" name="age" id="age" value="<?php if (isset($age)) { echo $age; }?>"><br><?php
if (isset($errorMsg3)){
echo $errorMsg3;
} ?><br><br>
<input type="submit" value="Submit"><input type="reset">
</form> <?php } ?>
</div>
final_page.php
<?php
session_start();
$title = $_SESSION['title'];
$fName = $_SESSION['fName'];
$lName = $_SESSION['lName'];
$age = $_SESSION['age'];
?>

How to set field value as the result of a calculation

I have a form that has a field whose value is from a php calculation. The Calculation is just basic arithmetic involving purely whole numbers. But there is a scenario where the value will be zero. So the form assumes that that filed has been left empty.
How can i go round that ?
Here is a sample of code.
if (
isset($_POST['input1']) &&
isset($_POST['input2']) &&
isset($_POST['ans'])
)
{
// CHECKING IF ANY OF THE FIELDS WERE LEFT EMPTY
$input1 = $_POST['input1'];
$input2 = $_POST['input2'];
$ans = ($input1)-($input2);
$ans_set = 0;
if ($ans === $ans_set ) {
# code...
//echo "Same";
$ans = '0';
} else {
# code...
//echo "Different";
echo "Check data types";
}
if (
!empty($input1) &&
!empty($input2) &&
!empty($ans)
)
{
$query = "INSERT INTO formaths VALUES ( 'NUll', NOW(),
'".mysql_real_escape_string($input1)."',
'".mysql_real_escape_string($input2)."',
'".mysql_real_escape_string($ans)."' )";
$query_run = mysql_query($query);
if ( $query_run )
{
//header("Location:". __DIR__."../registration_success.php");
echo "<p class='echo'>Data entry was successful.</p>";
}
else
{
echo "<p class='echo'>It seems that we couldn't save that at this time.</p>";
}
}
else
{
echo "<p class='echo'>Please make sure all fields are filled and are correct.<br/>You must fill in the area field last!</p>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="formaths.php" method="POST">
<input name="input1" type="text" autofocus/>
<input name="input2" type="text"/>
<input name="ans" type="text" value="<?php if (isset($ans)) { echo $ans; }?>" readonly />
<input type="submit" value="DO IT" />
</form>
enter code here
</body>
</html>

Categories