Problems inserting data into MYSQL database using PHP - php

I am still a beginner at PHP/MYSQL and I am having difficulties inserting data into my MYSQL database. (I've originally tried using my localhost database but once i moved to an online server, everything seems to stop working.)
Right now, as soon as i submit the data from my index.php page.. it only refreshes the page and doesn't add any data.
However, when I go to submit.php, everything works fine and it adds an empty set of data to my results.php.
My codes are as follows. Any help will be greatly appreciated. Thank you!
Index.php
<html>
<head>
<title>POST variables</title>
<link rel="stylesheet" type="text/css" href="css/style.css" media="all">
</head>
<body>
<?php
$con = mysqli_connect('localhost', 'anas12_test', 'a1b2c3d4', 'anas12_test');
if (!$con) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo '<div class="container">
<form id="profiles">
<div class="header">
<h3>Hello there!</h3>
<p>We want to know more about you! Share a few interesting details about yourself using the form below!</p>
</div>
<div class="sep"></div>
<div class="inputs">
<form action="submit.php" method="post">
<input id="name" name="name" placeholder="Full Name" required="" autofocus="" autocomplete="on" type="text">
<input id="email" name="email" placeholder="Email Address" required="" autofocus="" autocomplete="on" type="text">
<input id="colour" name="colour" placeholder="Favourite Colour" required="" autofocus="" autocomplete="on" type="text">
<input id="music" name="music" placeholder="Favourite Song" required="" autofocus="" autocomplete="on" type="text">
<input id="superpower" name="superpower" placeholder="If you had a superhero ability, what would it be?" required="" autofocus="" autocomplete="on" type="text">
<button id="submit" type="submit"name="submit" value="added">Submit!</button>
</form> </div>
</div>';
?>
</body>
</html>
Submit.php
$con = mysqli_connect('localhost', 'anas12_test', 'a1b2c3d4', 'anas12_test');
if(isset($_POST["name"])){
$name = $_POST["name"];
} else {
$name = "";
}
if(isset($_POST["email"])){
$email = $_POST["email"];
} else {
$email = "";
}
if(isset($_POST["colour"])){
$colour = $_POST["colour"];
} else {
$colour = "";
}
if(isset($_POST["music"])){
$music = $_POST["music"];
} else {
$music = "";
}
if(isset($_POST["superpower"])){
$superpower = $_POST["superpower"];
} else {
$superpower = "";
}
$sql = "INSERT INTO profiles (name, email, colour, music, superpower) VALUES ('$name', '$email', '$colour', '$music', '$superpower')";
if(mysqli_query($con, $sql)){
header ('location: results.php'.$query_string);
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($con);
}
if($name !== "" && $email !== "" && $colour !== "" && $music !== "" && $superpower !== "") {
$query_string = '?name=' . $name.'&email='.$email.'&colour='.$colour.'&music='.$music.'&superpower='.$superpower;
header('HTTP/1.1 303 See Other');
header ('location: results.php'.$query_string);
}
?>
And my results page.
<html>
<head>
<title>POST Success</title>
</head>
<body>
<?php
$con = mysqli_connect('localhost', 'anas12_test', 'a1b2c3d4', 'anas12_test');
if(isset($_GET["name"])){
$name = $_GET["name"];
} else {
$name = "no name";
}
if(isset($_GET["email"])){
$email = $_GET["email"];
} else {
$email = "no email";
}
if(isset($_GET["colour"])){
$colour = $_GET["colour"];
} else {
$colour = "no colour:";
}
if(isset($_GET["music"])){
$music = $_GET["music"];
} else {
$music = "music";
}
if(isset($_GET["superpower"])){
$superpower = $_GET["superpower"];
} else {
$superpower = "superpower";
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT * FROM profiles");
echo "<div style='border:solid 1px #ccc;padding:10px;float:left;margin-top:10px;'>";
echo "<table border='1'> <tr> <th>Name</th> <th>Email</th> <th>Favourite Colour</th>
<th>Favourite Music</th>
<th>Superhero Ability</th>
</tr>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['colour'] . "</td>";
echo "<td>" . $row['music'] . "</td>";
echo "<td>" . $row['superpower'] . "</td>";
echo "</tr>";}
echo "</table>";
echo "</div>";
mysqli_close($con);
?>
</body>
</html>

Your form has no action, so it'll submit the form to the URL you loaded the page from, which will be index.php.
You need this:
<form id="profiles" action="Submit.php" method="POST">
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Note the method portion as well - with no method, forms default to using GET

Be careful you have two form in your index.php.
<form id="profiles">
and
<form action="submit.php" method="post">
I think the first one is useless.

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>

How to change form action thru if else statement on PHP?

How I can change the form action thru if else statement that will redirect to other PHP page?
I'm new to PHP, thankyou in advance
here is my code:
<?php
if(isset($_POST['btn_submit']))
{
$Fname = $_POST['Fname'];
$Lname = $_POST['Lname'];
$sel = "SELECT Lname FROM users WHERE Fname='" . $Fname . "'";
$result = $conn->query($sel);
if($result->num_rows>0)
{
while($row = $result->fetch_assoc())
{
$Lname = $row['Lname'];
}
if ($Lname == $Lname)
{
echo "Correct data!";
/*i want to put redirect page here*/
}
else
{
echo "invalid Firsname!";
}
}
else
{
echo "invalid Lastname!";
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="text" name="Fname" placeholder="Enter your Fname" required>
<input type="text" name="Lname" placeholder="Lname" required>
<input type="submit" name="btn_submit" value="Sign In">
</form>
example
if ($_POST['p'] == 1) { $insertGoTo = "t1.php"; }
if ($_POST['p'] == 2) { $insertGoTo = "t2.php"; }
header(sprintf("Location: %s", $insertGoTo));
?

PHP won't insert data to Mysql database - No error thrown

Hi so I can't seem to find any help on this topic because there is no error being thrown. I am trying to insert records to a database via php using mysqli_query but after the re-direct no changes are made. I have three files I am working with, index.php, conn.php and new.php. index.php and new.php are located in the same folder but conn.php is one directory below.
index.php:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" type="text/css" >
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Khula" rel="stylesheet">
</head>
<script>
$(function()
{
$('.error').fadeOut(10000);
});
</script>
<body>
<header>
<img src="images/logo.png">
<p>The reliable bus company</p>
</header>
<div class="wrapper">
<div class="container">
<div class="titletxt">
<h4>Drivers</h4>
</div>
<?php
include '../conn.php';
mysqli_query($conn, "SET NAMES utf8");
$result = mysqli_query($conn, "SELECT * FROM tbl_employee");
echo "
<div class='table_content'>
<table align='center'>
<tr>
<th>Employee ID</th>
<th>Title</th>
<th>Name</th>
<th>Address</th>
<th>Contact Number</th>
<th>Job Position</th>
<th>Gender</th>
<th>DOB</th>
</tr>
";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['employeeID'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['contactNum'] . "</td>";
echo "<td>" . $row['position'] . "</td>";
echo "<td>" . $row['gender'] . "</td>";
echo "<td>" . $row['DOB'] . "</td>";
echo "</tr>";
}
echo "</table></div>";
?>
<!-- Record Insert -->
<br>
<div class="titletxt">
<h4>Insert a Record</h4>
</div>
<h3 style="font-weight: 400; margin-left: 5px;">New Employee</h3>
<form class="insert_form" action="new.php" method="post" name="insert_form">
<label>Title: </label>
<input type="text" name="title" required><br>
<span class="error"><?php echo $titleErr ?></span>
<br>
<label>Name: </label>
<input type="text" name="name" required> <br>
<span class="error"><?php echo $nameErr ?></span>
<br>
<label>Address:</label>
<input type="text" name="address" required><br>
<span class="error"><?php echo $addressErr ?></span>
<br>
<label>Contact Number</label>
<input type="text" name="contactNum" required><br>
<span class="error"><?php echo $contactErr ?></span>
<br>
<label>Job Position</label>
<input type="text" name="position" required><br>
<span class="error"><?php echo $positionErr ?></span>
<br>
<label>Gender: </label>
<input type="radio" name="gender" value="male" required> Male
<input type="radio" name="gender" value="female" required> Female<br>
<span class="error"><?php echo $genderErr ?></span>
<br>
<label>DOB: </label>
<input style="width: 60px;" type="text" name="DOB_year" required>YYYY
<input style="width: 30px;" type="text" name="DOB_months" required>MM
<input type="text" name="DOB_day" style="width: 30px" required>DD<br>
<span class="error"><?php echo $DOBErr ?></span>
<br>
<input type="submit" Value="Insert Entry">
</form>
</div>
</div>
</body>
</html>
conn.php:
<?php
$server = "localhost";
$user = "root";
$password = "";
$db = "bus_db";
global $conn;
$conn = mysqli_connect($server, $user, $password, $db);
if(mysqli_connect_errno())
{
echo "Mysql Error has occured" . mysqli_connect_error;
}
else if(!mysqli_connect_errno())
{
echo "<connection>Connection Established</connection>";
}
function close_connection()
{
global $conn;
mysqli_close($conn);
}
$title = $name = $address = $contact = $position = $gender = $DOB = "";
$titleErr = $nameErr = $addressErr = $contactErr = $positionErr = $genderErr = $DOBErr = "";
mysqli_query($conn, "SET NAMES utf8");
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["title"]))
{
$titleErr = "Title is Required";
}else{
$title = input($_POST["title"]);
}
if (empty($_POST["name"]))
{
$nameErr = "Name is Required";
}else
{
$name = input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Invalid Name";
}
}
if (empty($_POST["address"]))
{
$addressErr = "Address is Required";
}else{
$address = input($_POST["address"]);
}
if (empty($_POST["contactNum"]))
{
$contactErr = "Contact Number is required ";
}else{
$contact = input($_POST["contactNum"]);
$regex = "^([0-9]{10,11})$^";
if (!preg_match($regex, $contact)) {
$contactErr = "Invalid Phone Number";
}
}
if(empty($_POST["position"]))
{
$positionErr = "Position is required";
}else{
$position = input($_POST["position"]);
}
if (empty($_POST["gender"]))
{
$genderErr = "Gender is Required";
}else{
$gender = input($_POST["gender"]);
}
if (empty($_POST["DOB_year"]) || empty($_POST["DOB_months"]) || empty($_POST["DOB_day"]))
{
$DOBErr = "Invalid entry for date of birth";
}else
{
$DOB = input($_POST["DOB_year"] + "/" + $_POST["DOB_months"] + "/" + $_POST["DOB_day"]);
}
}
function input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function insert_records($p_title, $p_name, $p_address, $p_contact, $p_position, $p_gender, $p_DOB)
{
global $conn;
mysqli_query($conn, "INSERT INTO tbl_employee VALUES(null, '" .$p_title."', '".$p_name."', '".$p_address."', '".$p_contact."', '".$p_position."', '".$p_gender."', '".$p_DOB."')");
}
?>
new.php:
<?php
include '../conn.php';
insert_records($title, $name, $address, $contact, $position, $gender, $DOB);
header( 'Location:index.php');
close_connection();
?>
I would appreciate any, thanks
You should edit your insert_records() to give you feedback if mysqli_query fails.
function insert_records($p_title, $p_name, $p_address, $p_contact, $p_position, $p_gender, $p_DOB)
{
global $conn;
$result = mysqli_query($conn, 'some query') or die('Query failed: ' . mysqli_error($conn));
return $result;
}
and read about how you can prevent MySQL injection here: How can I prevent SQL injection in PHP?
edit:
$DOB = input($_POST["DOB_year"] + "/" + $_POST["DOB_months"] + "/" + $_POST["DOB_day"]);
in php '+' is used to do calculations. if you want to concatenate strings use '.'
$DOB = input($_POST["DOB_year"] . "/" . $_POST["DOB_months"] . "/" . $_POST["DOB_day"]);

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'];
?>

PHP form not displaying feedback

I'm making a process form in PHP and I'm trying to display the feedback but it's not wanting to show. The code that I have is:
<html>
<head>
<style type="text/css">
.error{color: #FF0000;}
</style>
</head>
<body>
<h1>Customer Feedback</h1>
<p1>Please tell us what you think</p1><br><br>
<?PHP
$name = trim($_POST[fullname]);
$email = trim($_POST[email]);
$text = trim($_POST[feedback]);
?>
<form method='POST' action='<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>' >
<p1>Your name:</p1><br>
<input type="text" name="fullname" value="<?php echo $fullname; ?>" required><br><br>
<p1>Your email address:</p1><br>
<input type="text" name="email" value="<?php echo $email; ?>" required><br><br>
<p1>Your feedback:</p1><br>
<textarea rows="5" cols="50" name="feedback"><?php echo nl2br($text);?></textarea>
<textarea><?php echo $text;?></textarea><br><br>
<input type="submit" Value="Send Feedback"><br><br>
</form>
<?php
if(isset($_POST[fullname]) && $_POST[fullname] != "" && !empty($_POST[fullname])) {
echo "Hi " . $name . ".<br>";
}
else{
echo "Please enter a name....";
}
if(isset($_POST[email]) && $_POST[email] != "" && !empty($_POST[email]) {
echo "Your email is " . $email . ".<br>";
}
else{
echo "Please enter a email address.";
}
if(isset($_POST[feedback]) && $_POST[feedback] != "") {
echo "Your feedback is:" . $feedback . "<br>";
}
else{
echo "No feedback.";
}
?>
</body>
</html>
When I run the page, it shows the name, email and 'Your feedback is: ' but not the feedback that was entered into the textarea.
EDIT
I want to use the nl2br() function round the text box.
Change following line to:
echo "Your feedback is:" . $text . "<br>";
Because you've never assign a value to $feedback variable.
Your code had too many errors I have corrected it, please fin the working code below:
<html>
<head>
<style type="text/css">
.error{color: #FF0000;}
</style>
</head>
<body>
<h1>Customer Feedback</h1>
<p1>Please tell us what you think</p1><br><br>
<?PHP
$name = trim($_POST[fullname]);
$email = trim($_POST[email]);
$text = trim($_POST[feedback]);
?>
<form method='POST' action='<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>' >
<p1>Your name:</p1><br>
<input type="text" name="fullname" value="<?php echo $fullname; ?>" required><br><br>
<p1>Your email address:</p1><br>
<input type="text" name="email" value="<?php echo $email; ?>" required><br><br>
<p1>Your feedback:</p1><br>
<textarea rows="5" cols="50" name="feedback"><?php echo nl2br($text);?></textarea>
<textarea><?php echo $text;?></textarea><br><br>
<input type="submit" Value="Send Feedback"><br><br>
</form>
<?php
if(isset($_POST['fullname']) && $_POST['fullname'] != "" && !empty($_POST['fullname'])) {
echo "Hi " . $name . ".<br>";
}
else{
echo "Please enter a name....";
}
if($_POST['email'] && $_POST['email'] != "" && $_POST['email']) {
echo "Your email is " . $email . ".<br>";
}
else{
echo "Please enter a email address.";
}
if(isset($_POST['feedback']) && $_POST['feedback'] != "") {
echo "Your feedback is:" . $_POST['feedback'] . "<br>";
}
else{
echo "No feedback.";
}
?>
</body>
</html>

Categories