redirect with post data is possible? - php

I need help with 'Confirm Form Resubmission' message (getting in chrome while watching view source)
If I delete the comment, it's shows only username 1 not matter which ID I selected, and if the comment stay as below code, its works with the re submit message...
<?php
$username = get_username_from_db(1);
if (isset($_POST['id'])) {
$id = $_POST['id'];
$username = get_username_from_db($id);
/*
// if this comment stay as comment, username will update with 'confirm form resubmission' message
// else 'confirm form resubmission' message not shows but username not updated (keep as default [1])
header('Location: ' . $_SERVER['HTTP_HOST']);
exit();
*/
}
?>
<body>
<form method="POST">
<fieldset>
<legend>Choose ID</legend>
<select name="id" onchange="this.form.submit()">
<option value="1">1st</option>
<option value="2">2nd</option>
<option value="3">3rd</option>
</select>
<br>
<label>Username:</label>
<input type="text" name="username" value="<?php echo $username; ?>">
</fieldset>
</form>
</body>
Any idea?

Try this:
Code with $_GET;
<?php
$username = get_username_from_db(1);
if (isset($_POST['id'])) {
$id = $_POST['id'];
$username = get_username_from_db($id);
/*
// if this comment stay as comment, username will update with 'confirm form resubmission' message
// else 'confirm form resubmission' message not shows but username not updated (keep as default [1])
*/
$url = $_SERVER['HTTP_HOST'] . '?name='.$username;
header('Location: ' . $url);
exit();
}
else if(isset($_GET['name']) && !empty($_GET['name'])){
$username = $_GET['name'];
}
?>
<body>
<form method="POST">
<fieldset>
<legend>Choose ID</legend>
<select name="id" onchange="this.form.submit()">
<option value="1">1st</option>
<option value="2">2nd</option>
<option value="3">3rd</option>
</select>
<br>
<label>Username:</label>
<input type="text" name="username" value="<?php echo $username; ?>">
</fieldset>
</form>
</body>
Code with $_SESSION;
<?php
session_start();
$user_id = 1;
if(isset($_SESSION['user_id'])){
$user_id = intval($_SESSION['user_id']);
}
// prevent 0 and negative;
if($user_id <= 0){
$user_id = 1;
}
$username = get_username_from_db($user_id);
if(isset($_POST['id'])){
$id = intval($_POST['id']);
// prevent 0 and negative;
if($id <= 0){
$id = 1;
}
$_SESSION['user_id'] = $id;
$url = $_SERVER['HTTP_HOST'];
header('Location: ' . $url);
exit();
}
?>
<body>
<form method="POST">
<fieldset>
<legend>Choose ID</legend>
<select name="id" onchange="this.form.submit()">
<option value="1">1st</option>
<option value="2">2nd</option>
<option value="3">3rd</option>
</select>
<br>
<label>Username:</label>
<input type="text" name="username" value="<?php echo $username; ?>">
</fieldset>
</form>
</body>

Related

Why is my first session in PHP not sending data to my second?

i'm trying to have one session that inputs data from the page into the post array, and then stores it to the session array which then sends it to a session 2 where I want the information to be displayed. My first session is sending me to my session 2 page but the information is not being displayed. Can anyone tell me if there is something wrong with my code? Thanks
Session 1
<?php
session_start();
if(isset($_POST["employeeNameBox"]))
{
$_SESSION["employeeName"] = $_POST["employeeNameBox"];
header("Location: Session2.php");
}
if(isset($_POST["employeeidBox"]))
{
$_SESSION["employeeid"] = $_POST["employeeidBox"];
header("Location: Session2.php");
}
if(isset($_POST["phoneNumberBox"]))
{
$_SESSION["phoneNumber"] = $_POST["phoneNumberBox"];
header("Location: Session2.php");
}
if(isset($_POST["emailBox"]))
{
$_SESSION["email"] = $_POST["emailBox"];
header("Location: Session2.php");
}
if(isset($_POST["positionBox"]))
{
$_SESSION["position"] = $_POST["positionBox"];
header("Location: Session2.php");
}
if(isset($_POST["ITProjectBox"]))
{
$_SESSION["ITProject"] = $_POST["ITProjectBox"];
header("Location: Session2.php");
}
?>
<html>
<body>
<?php include('Header.php'); ?>
<?php include('Menu.php'); ?>
<div class="content">
<form method="POST">
<input type="text" name="employeeNameBox" value="Employee name"> <br>
<input type="text" name="employeeidBox" value="Employee id"> <br>
<input type="text" name="phoneNumberBox" value="Phone number"> <br>
<input type="text" name="emailBox" value="Email"> <br>
<input type="radio" id="Manager" name="positionBox" value="Manager">
<label for="Manager">Manager</label><br>
<input type="radio" id="Team Lead" name="positionBox" value="Team Lead">
<label for="Team Lead">Team Lead</label><br>
<input type="radio" id="IT Developer" name="positionBox" value="IT Developer">
<label for="IT Developer">IT Developer</label><br>
<input type="radio" id="IT Analyst" name="positionBox" value="IT Analyst">
<label for="IT Analyst">IT Analyst</label><br><br>
<select name="ITProjectBox">
<option value="Project A">Project A</option>
<option value="Project B">Project B</option>
<option value="Project C">Project C</option>
<option value="Project D">Project D</option>
</select> <br><br>
<button type="submit">Submit Information</button>
</form>
</div>
</div>
<?php include('Footer.php'); ?>
</body>
</html>
Session 2
<?php
session_start();
if(isset($_SESSION["employeeName"]))
{
echo "<b>Employee name: </b>" .$_SESSION["employeeName"];
echo("<br><br>");
}
if(isset($_SESSION["employeeid"]))
{
echo("<b>Employee id: </b>" .$_SESSION["employeeid"]);
echo("<br><br>");
}
if(isset($_SESSION["phoneNumber"]))
{
echo("<b>Phone number: </b>" .$_SESSION["phoneNumber"]);
echo("<br><br>");
}
if(isset($_SESSION["email"]))
{
echo("<b>Email: </b>" . $_SESSION["email"]);
echo("<br><br>");
}
if(isset($_SESSION["position"]))
{
echo("<b>Position: </b>" . $_SESSION["position"]);
echo("<br><br>");
}
if(isset($_SESSION["ITProject"]))
{
echo("<b>IT Project: </b>" . $_SESSION["ITProject"]);
echo("<br><br>");
}
?>
<html>
<body>
<?php include('Header.php'); ?>
<?php include('Menu.php'); ?>
<div class="content">
</div>
<?php include('Footer.php'); ?>
</body>
</html>
First, make sure your session is saved before redirect, you can use session_write_close().
Second, make sure your script finish just after redirect, use exit.
You can use a function that makes both actions to economize code:
session_start();
if(isset($_POST["employeeNameBox"]))
{
$_SESSION["employeeName"] = $_POST["employeeNameBox"];
my_redirect('Session2.php');
}
//Here rest of vars
function my_redirect($to)
{
session_write_close();
header('Location: ' . $to);
exit;
}

PHP Simple Form Validation

I am trying to create a simple form validation and the form wont submit until all of the fields were set. I have two files here.
-form.php
-process.php
For some reason the $error won't appear and the radio button wont submit. Is there anything wrong?
here's the form.php:
<?php
if(isset($_GET['error']) && $_GET['error']!=""){
echo $_GET['error'];
}
?>
<body>
<form action="process.php" method="POST">
<p>
<label for="name">Your Name:</label>
<input type="text" name="name" id="name" value="">
</p>
<p>
<label for="location">Dojo Location:</label>
<select name="location">
<option value="Mountain View">Mountain View</option>
<option value="San Francisco">San Francisco</option>
<option value="South Korea">South Korea</option>
<option value="Philippines">Philippines</option>
</select>
</p>
<p>
<label for="language">Favorite Language:</label>
<select name="language">
<option value="JavaScript">JavaScript</option>
<option value="PHP">PHP</option>
<option value="Ruby">Ruby</option>
<option value="Python">Python</option>
</select>
</p>
<p>
<label for="comment">Comment: (Optional)</label><br/>
<textarea rows="10" cols="50" name="comment"></textarea>
</p>
<p>
<label for="comment">Can we store cookies in your computer?</label>
<input type="radio" name="cookies" value="yes">Yes
<input type="radio" name="cookies" value="no">No
</p>
<input type="submit" value="Submit">
</form>
here's the process.php:
<?php
if (isset($_POST["submit"])) {
if (empty($_POST["name"])) {
$Error = "Missing Name";
}
if (empty($_POST["location"])) {
$Error = "Missing Location";
}
if (empty($_POST["language"])) {
$Error = "Missing language";
}
if (empty($_POST["cookies"])) {
$Error = "Select cookies";
}
}else{
$name = $_POST['name'];
$location = $_POST['location'];
$language = $_POST['language'];
$comment = $_POST['comment'];
$cookies = $_POST['cookies'];
}
if($Error!=""){
header("Location:form.php?error=".$Error);
}
?>
<h2>Submitted Information:</h2>
<p><?php echo "NAME: {$name}"; ?> </p>
<p><?php echo "DOJO LOCATION: {$location}"; ?></p>
<p><?php echo "FAVORITE LANGUAGE: {$language}:"; ?> </p>
<p><?php echo "COMMENT: {$comment}"; ?></p>
<p><?php echo "COOKIES: {$cookies}"; ?></p>
Any idea?
Try something like this in your process.php
if($Error!=""){
header("Location:form.php?error=".$Error);
}
On your form.php
if(isset($_GET['error']) && $_GET['error']!=""){
echo $_GET['error'];
}
In your process.php change the code to
<?php
if (isset($_POST["submit"])) {
$Error ="";
if (isset($_POST["name"]) && $_POST["name"]!="") {
$Error = "Missing Name";
}
if (isset($_POST["location"]) && $_POST["location"]!="") {
$Error = "Missing Location";
}
if (isset($_POST["language"]) && $_POST["language"]!="") {
$Error = "Missing language";
}
if (isset($_POST["cookies"]) && $_POST["cookies"]!="") {
$Error = "Select cookies";
}
if($Error!=""){
header("Location:form.php?error=".$Error);
}
$name = $_POST['name'];
$location = $_POST['location'];
$language = $_POST['language'];
$comment = $_POST['comment'];
$cookies = $_POST['cookies'];
}
?>
Either you need a form to redirect back to your form.php, or move the echo $Error to your process.php so you can show the error from that page.

I'm trying to insert SQL query but nothing inserting in database

I'm trying to do simple script with PHP and insert some data, but nothing happens! I knew that I missed something but what is it?
This my code:
<?php
$host= "localhost";
$user="root";
$pass="freedoom19";
$db="dddd";
$con = mysqli_connect($host,$user,$pass,$db) or mysql_error();
//====== Get Variable======= //
$name = $_POST['name'];
$email=$_POST['email'];
$rate=$_POST['select_style'];
$content=$_POST['content'];
$insert="insert into reviews (name,email,rate,content) values ('$name','$email','$rate','$content')";
//====== Get Variable======= //
if($_POST['submit-comment']) {
if($name && $email && $content == true) {
mysqli_query($con,$insert);
$success = "<span class='success_testmonial'>Thank You! .. Your Raiting Has Been Submitted And We Will Post It As Soon We Verify It !</span>";
}
else {
$error = "<span class='error_testmonial'>Error : one or some fields has left empty .. Please fill all field and try again.</span>";
}
}
mysqli_close($con);
?>
And this it the form and the "action" ..
<form method="post" action="" id="form-contact" class="clearfix">
<div id="form-left">
<label for="text-name">Name *</label><br />
<input type="text" name="name" class="input" id="text-name" /><br />
<label for="text-email">From *</label><br />
<input type="text" name="email" class="input" id="text-email" /><br />
<label for="text-phone">Rate us *</label><br />
<div class="select-style">
<select>
<option value="5.0">5.0</option>
<option value="4.5">4.5</option>
<option value="4.0">4.0</option>
<option value="3.5">3.5</option>
<option value="3.0">3.0</option>
<option value="2.5">2.5</option>
<option value="2.0">2.0</option>
<option value="2.0">2.0</option>
<option value="1.5">1.5</option>
<option value="1.0">1.0</option>
</select>
</div>
</div>
<div id="form-right">
<label for="text-comment">Review <span></span></label><br />
<textarea name="content" cols="10" rows="20" class="input textarea" id="text-comment"></textarea><br />
<input type="submit" name="submit-comment" class="button" value="Rate Us" />
</div>
<p id="text-contact">
<br><br><font color="#980303">Please Note *</font> Thate Your Reviews Will Not Published Untill We Check it and sure that the review don't contain Bad words or bad language, and be sure that we will publish all reviews and we accept criticism!
</form>
So what I missed please?
Check this working code. Also you had not set element name for Drop down as select_style. It was throwing error for that too.
PHP Code
if(isset($_POST['submit-comment']) && $_POST['submit-comment']!='') {
$host= "localhost";
$user="root";
$pass="";
$db="test";
$con = mysqli_connect($host,$user,$pass,$db) or mysql_error();
//====== Get Variable======= //
$name = mysqli_real_escape_string($con,$_POST['name']);
$email = mysqli_real_escape_string($con,$_POST['email']);
$rate = mysqli_real_escape_string($con,$_POST['select_style']);
$content = mysqli_real_escape_string($con,$_POST['content']);
$insert="insert into reviews (name,email,rate,content) values ('$name','$email','$rate','$content')";
if($name && $email && $content == true) {
mysqli_query($con,$insert);
$success = "<span class='success_testmonial'>Thank You! .. Your Raiting Has Been Submitted And We Will Post It As Soon We Verify It !</span>";
echo $success;
}
else {
$error = "<span class='error_testmonial'>Error : one or some fields has left empty .. Please fill all field and try again.</span>";
echo $error;
}
mysqli_close($con);
}
HTML
<form method="post" action="" id="form-contact" class="clearfix">
<div id="form-left">
<label for="text-name">Name *</label><br />
<input type="text" name="name" class="input" id="text-name" /><br />
<label for="text-email">From *</label><br />
<input type="text" name="email" class="input" id="text-email" /><br />
<label for="text-phone">Rate us *</label><br />
<div class="select-style">
<select name="select_style">
<option value="5.0">5.0</option>
<option value="4.5">4.5</option>
<option value="4.0">4.0</option>
<option value="3.5">3.5</option>
<option value="3.0">3.0</option>
<option value="2.5">2.5</option>
<option value="2.0">2.0</option>
<option value="2.0">2.0</option>
<option value="1.5">1.5</option>
<option value="1.0">1.0</option>
</select>
</div>
</div>
<div id="form-right">
<label for="text-comment">Review <span></span></label><br />
<textarea name="content" cols="10" rows="20" class="input textarea" id="text-comment"></textarea><br />
<input type="submit" name="submit-comment" class="button" value="Rate Us" />
</div>
<p id="text-contact">
<br><br><font color="#980303">Please Note *</font> Thate Your Reviews Will Not Published Untill We Check it and sure that the review don't contain Bad words or bad language, and be sure that we will publish all reviews and we accept criticism!
</form>
try to put your get variables inside the if else statement
check if there are datas in POST when done submitting:
if($_POST['submit-comment']) {
$name = $_POST['name'];
$email=$_POST['email'];
$rate=$_POST['select_style'];
$content=$_POST['content'];
$insert="insert into reviews (name,email,rate,content) values ('$name','$email','$rate','$content')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
var_dump($_POST);
}
$con->close();
check for errors:
$check = mysqli_query($con,$insert);
var_dump($check);
if you found one, let me know
Note:
Put your insert query and passed on variables (POST) inside your if statement isset(POST["submit-comment"] to eliminate errors of undefined variables.
You should use mysqli_* prepared statement instead to prevent SQL injections.
Answer:
If you insist on retaining your code, you can use mysqli_real_escape_string() function to fertilize a bit the content of your variables before using it in your query.
Your PHP file should look like this:
<?php
$host= "localhost";
$user="root";
$pass="freedoom19";
$db="cookindoor";
$con = mysqli_connect($host,$user,$pass,$db) or mysql_error();
//====== IF SUBMIT-COMMENT ======= //
if(isset($_POST['submit-comment'])) {
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["content"])) {
//====== GET VARIABLES ======= //
$name = mysqli_real_escape_string($con,$_POST['name']);
$email = mysqli_real_escape_string($con,$_POST['email']);
$rate = mysqli_real_escape_string($con,$_POST['select_style']);
$content = mysqli_real_escape_string($con,$_POST['content']);
$insert="INSERT INTO reviews (name,email,rate,content) VALUES ('$name','$email','$rate','$content')";
mysqli_query($con,$insert);
$success = "<span class='success_testmonial'>Thank You! .. Your Raiting Has Been Submitted And We Will Post It As Soon We Verify It !</span>";
}
else {
$error = "<span class='error_testmonial'>Error : one or some fields has left empty .. Please fill all field and try again.</span>";
}
}
mysqli_close($con);
?>
Recommendation:
But if you execute it in mysqli_* prepared statement, your insert query would look like this. Though this is just a simple example but still executable:
if($stmt = $con->prepare("INSERT INTO reviews (name, email, rate, content) VALUES (?,?,?,?)")){ /* CHECK THE QUERY */
$stmt->bind_param('ssss', $_POST["name"], $_POST["email"], $_POST["rate"], $_POST["content"]); /* BIND VARIABLES TO YOUR QUERY */
$stmt->execute(); /* EXECUTE YOUR QUERY */
$stmt->close(); /* CLOSE YOUR QUERY */
}

PHP file upload into mysql

I have created a form as follows. What I'm doing is
User is selecting a client from drop down list and uploading file. When he clicks on Add button the page will redirect to Confirm.php.
The Confirm.php will show whatever the user has given the input i.e, Client name and name of the file which he has uploaded.
In Confirm.php the user is submitting the form and it should add to the database, except file upload remaining fields are adding to the database. In database, file upload field is showing empty. Please somebody solve this problem.
And I'm not getting how to access path variable from Confirm.php into Add.php.
I'm new to the php. So any help will be appreciated.
Thank you.
Home.php
<form action="Confirm.php" method="post" enctype="multipart/form-data" novalidate>
<label> <span>Client</span>
<select class="required" name="client">
<?php
mysql_connect ("localhost","root","");
mysql_select_db ("eservice");
$select="eservice";
if (isset ($select)&&$select!="")
{
$select=$_POST ['NEW'];
}
?>
<?php
$list=mysql_query("select * from client");
while($row_list=mysql_fetch_assoc($list))
{
?>
<?php $ct = $row_list['cname'];?>
<option value="<?php echo $ct; ?>"<?php if($ct==$select){ echo "selected"; } ?> > <?php echo $ct; ?></option>
<?php } ?>
</select>
</label>
<label> <span>SRN</span>
<?php
$con=mysqli_connect("localhost","root","","eservice");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="Select * from main";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
$rowcount++;
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
<input name="srn" type="text" id="srn" size="15" readonly="readonly" maxlength="40" value="<?php echo "$rowcount"; ?>"/>
</label>
</div>
<label>
<span>File upload</span>
<input type="file" name ="filename" required>
</label>
<button id='send' type='submit'>Add</button>
<button id='clear' type='reset'>Reset</button>
</form>
And this is my cofirmation page
Confirm.php
<form action="Add.php" method="post" enctype="multipart/form-data" novalidate>
<label> <span>Client</span>
<?php include_once('dbconn.php'); ?>
<input name="client" type="text" id="client" size="15" readonly="readonly" maxlength="40" value="<?php echo $_POST['client']; ?>"/>
</label>
<label>
<span>File upload</span>
<?php $path = '';
$folder = "Folder/";
if (is_uploaded_file($_FILES['filename']['tmp_name']))
{
if (move_uploaded_file($_FILES['filename']['tmp_name'], $folder.$_FILES['filename']['name']))
{
$path = $folder . $_FILES['filename']['name'];
}
else
{
$path = '';
};
}
else
{
$path = '';
}; ?>
<input name ="filename" readonly="readonly" value="<?php echo $_FILES['filename']['name']; ?>"/>
</label>
<button id='clear' type='reset'>Back</button>
<button id='send' type='submit'>Add</button>
</form>
dbconn.php
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("eservice",$dbhandle)
or die("Could not select newsite database");
?>
Here I'm adding the uploaded file into the phpmyadmin.
Add.php
<?php
include_once('dbconn.php');
session_start();
$_SESSION['example']='Session Created';
$client = $_POST['client']; // required
if($client !='')
{
$insQry = "Insert into `main` (client,upload) Values ('$client','$path')";
$insertQ = mysql_query($insQry);
if($insertQ!=''){
echo "<h2>Data inserted successfully...</h2>";
} else {
echo "<h2>Not added</h2>";
}
}
?>
Undefined Index means if that index is not set or empty...you have to check is it empty or not.
add condition in filename error
if ( $_FILES['filename']['error'] == 0 ){
///your uploading code
}
and for post veriable check it is isset or not, use ternary operator:-
$client =isset( $_POST['client'])?$_POST['client']:'';
Your confirm.php code should be
<form action="Add.php" method="post" enctype="multipart/form-data" novalidate>
<label> <span>Client</span>
<?php include_once('dbconn.php'); ?>
<input name="client" type="text" id="client" size="15" readonly="readonly" maxlength="40" value="<?php echo $_POST['client']; ?>"/>
</label>
<label>
<span>File upload</span>
<?php $path = '';
$folder = "Folder/";
if (is_uploaded_file($_FILES['filename']['tmp_name']))
{
if (move_uploaded_file($_FILES['filename']['tmp_name'], $folder.$_FILES['filename']['name']))
{
$path = $folder . $_FILES['filename']['name'];
}
else
{
$path = '';
};
}
else
{
$path = '';
}; ?>
<input name ="filename" readonly="readonly" value="<?php echo $_FILES['filename']['name']; ?>"/>
<input name ="path" type="hidden" value="<?php echo $path; ?>"/>
</label>
<button id='clear' type='reset'>Back</button>
<button id='send' type='submit'>Add</button>
</form>
You can get your hidden field value on add.php using $path = $_POST['path']

The form is sent without validation: php mysql

I have tried the following php script to validate the user input.But the form is sent to database without prompting the user to fill the required fields i.e if a user leaves one or more fields empty, the form is submitted without asking to fill the fields.How do stop it from submitting until the conditions for each form field are met?
here is the code:-
<?php
$fnameErr=$lnameErr=$emailErr=$passwordErr=$cpasswordErr="";
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
if(empty($_POST["fname"]))
{
$fnameErr="First name is Required";
}
else
{
$fname = $_POST["fname"];
}
if (empty($_POST["lname"]))
{
$lnameErr = "Last Name is required";
}
else
{
$lname = $_POST["lname"];
}
if (empty($_POST["email"]))
{
$emailErr = "Email is required";
}
else
{
$email = $_POST["email"];
}
if (empty($_POST["password"]))
{
$passwordErr = "Password is required";
}
else
{
$password = $_POST["password"];
}
if (empty($_POST["cpassword"]))
{
$cpasswordErr = "Confirm Password";
}
else
{
$cpassword = $_POST["cpassword"];
}
//Create connection
$con=mysqli_connect("localhost","root","p11","daot");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO registration (FirstName, LastName, EmailAddress,Password,ConfirmPassword)
VALUES
('$_POST[fname]','$_POST[lname]','$_POST[email]','$_POST[password]','$_POST[cpassword]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mastercss.css">
<title>SIGN UP PAGE</title>
</head>
<body>
<?php include 'header.php'; ?>
<div class="leftbar">
</div>
<div class="content">
<h1 class="h1">complete the following form to register</h1>
<fieldset style="width:450px; background:gray;">
<form autocomplete="on" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label for="fname">First Name:</label>
<input type="text" name="fname"><?php echo $fnameErr;?><br><br>
<label for="lname">Last Name:</label>
<input type="text" name="lname"><?php echo $lnameErr;?><br><br>
<label for="email">Email:</label>
<input type="email" name="email"><?php echo $emailErr;?><br><br>
<label for="password">Password:</label>
<input type="password" name="password"><?php echo $passwordErr;?><br><br>
<label for="cpassword">Confirm Password</label>
<input type="password" name="cpassword"><?php echo $cpasswordErr;?><br><br>
<!--<label for="sex">Sex</label><input type="radio" name="sex" value="female"> Female
<input type="radio" name="sex" value="male">Male<br>
<label for="select">Birthday</label>
<select name="birthday_Month" id="month">
<option value="0" selected="1">Month</option>
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
</select>
<select name="birthday_day" id="month">
<option value="0" selected="1">Day</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="birthday_year" id="year">
<option value="0" selected="1">year</option>
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
</select><br><br>-->
<input type="submit" value="SIGN UP" style="width:100: height:100" name="Submit">
</form>
</fieldset>
</div>
<div class="rightbar"><br><br>
<a href="https://www.twitter.com"><img src="tw1.jpg">
<img src="fb2.jpg">
</div>
<?php include "footer.php";?>
</body>
</html>
The form is being submitted without showing validations because it is executing the following line of codes even after executing the validation conditions. You need to avoid executing of the code if any validation is not proper by exiting from the code segment.
if(empty($_POST["fname"]))
{
$fnameErr="First name is Required";
exit;
}
You should do this instead
if(empty($_POST["fname"]))
{
$fnameErr="First name is Required";
echo $fnameErr;
exit();
}
and same for the rest of the conditions.
This will display all your errors at once:
In your PHP:
$error = array(); //save all errors into one array, later we will check if this array is empty to proceed with saving into DB
if(empty($_POST["fname"]))
{
$error['fname']="First name is Required";
}
else
{
$fname = $_POST["fname"];
}
if (empty($_POST["lname"]))
{
$error['lname'] = "Last Name is required";
}
else
{
$lname = $_POST["lname"];
}
if (empty($_POST["email"]))
{
$error['email'] = "Email is required";
}
else
{
$email = $_POST["email"];
}
if (empty($_POST["password"]))
{
$error['password'] = "Password is required";
}
else
{
$password = $_POST["password"];
}
if (empty($_POST["cpassword"]))
{
$error['cpassword'] = "Confirm Password";
}
else
{
$cpassword = $_POST["cpassword"];
}
if (empty($errors)) {
//if there are no errors, save into DB
//Create connection
$con=mysqli_connect("localhost","root","p11","daot");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO registration (FirstName, LastName, EmailAddress,Password,ConfirmPassword)
VALUES
('$_POST[fname]','$_POST[lname]','$_POST[email]','$_POST[password]','$_POST[cpassword]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
}
}
And in your HTML:
<label for="fname">First Name:</label>
//checking if error message is set, if yes display it
<input type="text" name="fname"><?php echo isset($error['fname'])?$error['fname']:'' ;?><br><br>
<label for="lname">Last Name:</label>
<input type="text" name="lname"><?php echo isset($error['lname'])?$error['lname']:'' ;?><br><br>
<label for="email">Email:</label>
<input type="email" name="email"><?php echo isset($error['email'])?$error['email']:'' ;?><br><br>
<label for="password">Password:</label>
<input type="password" name="password"><?php echo isset($error['password'])?$error['password']:'' ;?><br><br>
<label for="cpassword">Confirm Password</label>
<input type="password" name="cpassword"><?php echo isset($error['cpassword'])?$error['cpassword']:'' ;?><br><br>

Categories