My data is not sended to database through PHP - php

I have a form on a website. I need to save my information to database. I made a database in localhost but when I click on submit it displays the whole code of register.php in the same page and no data saved in database,i have placed all the files in htdocs. I have form in index.html and register.php file is seperate. Here the php file:
<?php
mysql_connect('localhost','root','');
if(!$link){
die('could not connect: ' . mysql_error());
}
echo 'connected successfully';
mysql_select_db(learnqurandb);
$name = $_post['fullname'];
$email = $_post['email'];
$mobile = $_post['mobile'];
$country = $_post['country'];
$course = $_post['course'];
$skype_id = $_post['skype'];
if($name == ""){
echo "<script>alert('please enter your name')</script>";
exit();
}
if($email == ""){
echo "<script>alert('please enter your E-mail')</script>";
exit();
}
if($mobile == ""){
echo "<script>alert('please enter your Mobile Numbet')</script>";
exit();
}
if($country == ""){
echo "<script>alert('please enter your country name')</script>";
exit();
}
if($course == ""){
echo "<script>alert('please select your desire course')</script>";
exit();
}
if($skype_id == ""){
echo "<script>alert('please enter your Skype ID')</script>";
exit();
}
$check_skype_id = "select * from learnquran where skype = '$skype_id";
$count = mysql_query('$check_skype_id');
if(mysql_num_rows ($count) > 0){
echo"<script>alert('Skype_id $skype_id is already exists, please try another one.')</script>";
exit();
}
$query = "INSERT INTO registration (fullname,email,mobile,country,course,skype) values('$name','$email','$mobile','$country','$course','$skype_id')";
if(mysql_query ($query)){
echo "<script>alert('Registration Successfull')</script>";
}
}
?>
my html form is this
<div id="form_div">
<h2>Quick Registration</h2>
<form name="Form1" method="post" action="register.php" />
<label for="name">Name:</label>
<input type="text" name="fullname" id="fname" /><br><br>
<label for="email">Email:</label>
<input type="text" name="email" id="user_email" /><br><br>
<label for="mobile">Mobile:</label>
<input type="text" name="mobile" id="user_mobile" /><br><br>
<label for="country">Country:</label>
<input type="text" name="country" id="user_country" /><br><br>
<label for="skype">Skype ID:</label>
<input type="text" name="skype" id="skype_id" /><br><br>
<label for="course">Course:</label>
<select name="course" id="desired_course" ><br><br>
<option value="Select course..." selected>Select course</option><br>
<option value="Quran Reading">Quran Reading</option>
<option value="Memorizing the Holy Quran">Memorizing Holy Quran</option>
</select><br><br>
<input type="submit" class="submit" id="button1" value=""/>
</form>
</div>

You should be using PDO instead of mysql_connect as it has been deprecated as of PHP 5.5.0. Please view this tutorial on how to use PDO. Here's more information about it: http://php.net/manual/en/function.mysql-connect.php
https://www.youtube.com/watch?v=QtCdk459NFg&list=PLfdtiltiRHWHkDwEoZ29Q9FKtWVjA46HC
As for your code just displaying on your screen, make sure that your server has php enabled.

Related

Trying to output data which has been input by user

I'm having issues trying to output data which a user has inputted into a form.. It's a 2 block form, I'm just trying to save the data into 2 variables and then echo the variables. But I don't understand where I'm going wrong. Any help appreciated.
<?php
echo $problem = "";
if(isset($_POST['submit']) && $_POST['submit']=="submit"){
if(!empty($_POST['eWeight']) && $_POST['eWeight']!=''){
$eWeight = mysqli_real_escape_string($conn, trim($_POST['eWeight']));
} else {
$problem .= "Please enter a weight. <br/>";
}
if(!empty($_POST['gym']) && $_POST['gym']!=''){
$gym = mysqli_real_escape_string($conn, trim($_POST['gym']));
} else {
$problem .= "Please enter time at gym. <br/>";
}
echo $eWeight, $gym;
}
?>
<?php
if($conn){
echo "connected";
}
echo $problem;
echo $eWeight;
?>
<form class="pure-form pure-form-stacked" name="contact_weight">
<label for="eWeight">Enter Weight: </label> <input type="number" id="eWeight" name="eWeight" placeholder="88" required/>
<label for="gym">Enter Time at Gym: </label> <input type="number" id="gym" name="gym" placeholder="60" required/>
<button class="submit" type="submit">Submit Form</button>
</form>
You can do something like this
<?php
echo $problem = "";
if(isset($_POST['submit'])){
if(!empty($_POST['eWeight']) && $_POST['eWeight']!=''){
$eWeight = mysqli_real_escape_string($conn, trim($_POST['eWeight']));
} else {
$problem .= "Please enter a weight. <br/>";
}
if(!empty($_POST['gym']) && $_POST['gym']!=''){
$gym = mysqli_real_escape_string($conn, trim($_POST['gym']));
} else {
$problem .= "Please enter time at gym. <br/>";
}
echo $eWeight, $gym;
}
if($conn){
echo "connected";
}
echo $problem;
echo $eWeight;
?>
<form class="pure-form pure-form-stacked" name="contact_weight" action="" method="post">
<label for="eWeight">Enter Weight: </label> <input type="number" id="eWeight" name="eWeight" placeholder="88" required/>
<label for="gym">Enter Time at Gym: </label> <input type="number" id="gym" name="gym" placeholder="60" required/>
<button name="submit" class="submit" type="submit">Submit Form</button>
</form>

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 */
}

Page redirecting back to login page after insert to db

My site has a simplistic login that when you go to an adminSLP page it redirects to the admin login page if the user isnt logged in. Problem is that when you are logged in to the page and try say inserting a record with the form i posted below it redirects you back to the login page. I cant see where I am going wrong.
ADMIN SLP
session_start();
// Call this function so your page
// can access session variables
if ($_SESSION['adminloggedin'] != 1) {
// If the 'loggedin' session variable
// is not equal to 1, then you must
// not let the user see the page.
// So, we'll redirect them to the
// login page (login.php).
header("Location: adminLogin.php");
exit;
}
ADMIN LOGIN
session_start();
if ($_GET['login']) {
// Only load the
code below if the GET
// variable 'login' is set. You will
// set this when you submit the form
if ($_POST['adminusername'] == '******'
&& $_POST['adminpassword'] == '*******') {
// Load code below if both username
// and password submitted are correct
$_SESSION['adminloggedin'] = 1;
// Set session variable
header("Location: adminSLP.php");
exit;
// Redirect to a protected page
} else echo '<style>#falseLogin{display: block!important;}</style>';
// Otherwise, echo the error message
}
LOGIN FORM
<form method="POST" action="adminLogin.php?login=true" id="adminlogin" style="padding:0">
<label for="adminusername">Username:</label>
<input type="text" name="adminusername" autocomplete="off"><br/>
<label for="adminpassword">Password:</label>
<input type="password" name="adminpassword" autocomplete="off" /><br/>
<input type="submit" value="Login">
</form>
FORM MADE FOR INSERTING RECORDS TO A DB
<form id="trainingForm" method="post" action="" style="display:block;">
<div>
<h2 id="title" style="color:#c89d64;font-size:36px;font-family: 'RokkittRegular'; margin:0 0 15px; padding:30px 0 30px 0;font-weight:normal;">Add New SLP</h2>
<label for="first_name">First Name</label><input id="first_name" name="first_name" data-required="false" data-validation="length" data-validation-length="min4" type="text">
<label for="last_name">Last Name</label><input id="last_name" name="last_name" data-required="false" data-validation="length" data-validation-length="min4" type="text">
<label for="title">Title</label><input id="title" name="title" data-required="false" data-validation="length" data-validation-length="min4" type="text">
<label for="user_phone">Phone*</label><input id="user_phone" name="user_phone" type="tel" value="(123) 456-7890" data-required="true" onFocus="if(this.value == '(123) 456-7890') this.value='';">
<label for="user_email">Email*</label><input id="user_email" name="user_email" type="email" value="name#something.com" data-required="true" data-validation="email" onFocus="if(this.value == 'name#something.com') this.value='';">
<label for="state_name">License Held In:</label><select name='state_name[]' id="state_name" multiple>
<?php
$result = mysqli_query($con,'SELECT * FROM license_state');
$count = 1;
while($row = mysqli_fetch_array($result))
{
echo '<option value=' . $row['state_name'] . '>' . $row['state_name'] . '</option>';
}
?>
</select>
<span><label for="isChecked">May we post your information on our site?:</label>
<input type="radio" name="isChecked" value="1" checked="checked"><p>Yes</p>
<input type="radio" name="isChecked" value="0"><p>No</p></span>
<label for="asha_number">Asha# (Will Not Be Published)*</label><input id="asha_number" name="asha_number" data-required="true" data-validation="length" data-validation-length="min4" type="text">
<label for="practice_name">Practice Name*</label><input id="practice_name" name="practice_name" data-required="true" data-validation="length" data-validation-length="min4" type="text">
<label for="practice_location">Practice Location*</label><input id="practice_location" name="practice_location" data-required="true" data-validation="length" data-validation-length="min4" type="text">
<span><label for="telepracticeProvider">Are you a telepractice provider?:</label>
<input type="radio" name="telepracticeProvider" id="yes" value="Yes" ><p>Yes</p>
<input type="radio" name="telepracticeProvider" id="no" value="No" checked="checked"><p>No</p></span><br/>
<input type="hidden" id='user_id' name='user_id'/>
<br/><button name="submit" id="submit" type="submit">Submit</button>
</div>
</form>
insert to db
if(isset($_POST['submit']))
{// Create connection
$con=mysqli_connect("Speechvive.db.11357591.hostedresource.com","****","*****!","Speechvive");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$title = $_POST['title'];
$state_name = $_POST['state_name'];
$asha_number = $_POST['asha_number'];
$practice_name = $_POST['practice_name'];
$practice_location = $_POST['practice_location'];
$user_phone = $_POST['user_phone'];
$user_email = $_POST['user_email'];
$isChecked = $_POST['isChecked'];
$telepracticeProvider = $_POST['telepracticeProvider'];
$implodeStates = implode(', ',$state_name);
$insert = "INSERT INTO users ".
"(first_name,last_name, title, state_name, asha_number, practice_name, practice_location, user_phone, user_email, isChecked, telepracticeProvider) ".
"VALUES('$first_name','$last_name', '$title', '$implodeStates', $asha_number, '$practice_name', '$practice_location', '$user_phone', '$user_email', '$isChecked', '$telepracticeProvider')";
$insertData = mysqli_query( $con,$insert );
if(! $insertData )
{
die('Could not enter data: ' . mysql_error());
}
mysqli_close($con);?>
<script>window.location = "http://www.speechvive.com/adminSLP.php";//RELOAD THE CURRENT PAGE</script><?php
} else if(isset($_POST['save'])){
// Create connection
$con=mysqli_connect("Speechvive.db.11357591.hostedresource.com","Speechvive","Slp2014!","Speechvive");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$user_id = $_POST['user_id'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$title = $_POST['title'];
$state_name = $_POST['state_name'];
$asha_number = $_POST['asha_number'];
$practice_name = $_POST['practice_name'];
$practice_location = $_POST['practice_location'];
$user_phone = $_POST['user_phone'];
$user_email = $_POST['user_email'];
$isChecked = $_POST['isChecked'];
$telepracticeProvider = $_POST['telepracticeProvider'];
$implodeStates = implode(', ',$state_name);
$update = ("UPDATE users SET first_name='$first_name',last_name='$last_name', title='$title', state_name='$implodeStates', asha_number='$asha_number', practice_name='$practice_name', practice_location='$practice_location', user_phone='$user_phone', user_email='$user_email', isChecked='$isChecked', telepracticeProvider='$telepracticeProvider' WHERE user_id = $user_id");
$updateData = mysqli_query( $con,$update );
if(! $updateData )
{
die('Could not enter data: ' . mysqli_error($con));
}
mysqli_close($con);?>
<script>window.location = "http://www.speechvive.com/adminSLP.php";</script><?php
}
window.location = "http://www.speechvive.com/adminSLP.php";
why did you wrote this in insert to db part.. I think this is creating the problem

Checks In PHP are not working

I am working in PHP. i have made a form named as Donor.php and a connect it to database. Now I am trying to apply checks in on it in PHP. But their is a problem. As I have applied checks for empty fields in PHP on a form but these checks are not working. Please check out my code. As my work is stuck just because of this problem. My code file is here:
Donor.php
<?php
//error_reporting(0);
if(isset($_POST['submit'])){
$first_name=$_POST['firstname'];
$last_name=$_POST['lastname'];
$Country=$_POST['country'];
$City=$_POST['city'];
$Gender=$_POST['gender'];
$Email=$_POST['email'];
$Password=$_POST['pwd'];
include_once "connectionn.php";
$emailChecker=mysql_real_escape_string($Email);
$sql_email_check=mysql_query("Select Email FROM user WHERE Email='$emailChecker'");
$email_check=mysql_num_rows($sql_email_check);
if((empty($first_name)) ||(empty($last_name)) ||(empty($City)) ||(empty($Gender)) ||(empty($Email)) ||(empty($Password))) {
$errorMsg='We are sorry, but there appears to be a problem with the form you submitted.';
if (empty($first_name)) {
$errorMsg.='$var is either 0, empty, or not set at all';
header('Location: Donor.php');
}
if(empty($last_name)){
$errorMsg.='lastname';
header('Location: Donor.php');
}
if(empty($City)){
$errorMsg.='City';
header('Location: Donor.php');
}
if(empty($Gender)){
$errorMsg.='Gender';
header('Location: Donor.php');
}
if(empty($Email)){
$errorMsg.='email';
header('Location: Donor.php');
}
if(empty($Password)){
$errorMsg.='Password';
echo "$errorMsg.";
header('Location: Donor.php');
}
}else if($email_check>0){
$errorMsg="invalid";
}else{
$sql="INSERT INTO user (User_ID,First_Name, Last_Name, gender, city, Email, Password) VALUES (NULL,'$first_name', '$last_name','$Gender','$City','$Email','$Password')";
$result=mysql_query($sql);
$UserID="SELECT max(User_ID) as usr from user";
$userIDResult=mysql_query($UserID);
if($userIDResult === false)
{
die(mysql_error());
}
while($R=mysql_fetch_array($userIDResult)){
$usrID= $R['usr'];
}
$donor="INSERT INTO donor(User_ID, Country)Values('".$usrID."','$Country')";
$resultdonor=mysql_query($donor);
mysql_close();
header('Location: DonorPro.php');
}
}
?>
<?php
include "Header.php";
//include "registration.php";
?>
<div class="DonorDiv">
<h1>Lets Join:</h1>
<form name="input" action="" method="post" <?php print"$errorMsg"; ?>>
First Name: <input type="text" name="firstname" placeholder="First Name" id="r">
<?php print "$first_name";
// if (!isset($_POST['firstname'])) {
//echo '$var is either 0, empty, or not set at all';
//}
?>
Last Name: <input type="text" name="lastname" placeholder="Last Name" id="u" <?php print "$last_name";?>> <br>
Institution: <input type="text" name="country" placeholder="Institution" id="" <?php print "$Institution";?>>
City: <input type="text" name="city" placeholder="City" id="" <?php print "$City";?>><br>
Country: <input type="text" name="country" placeholder="Country" id="" <?php print "$Country";?>><br>
Gender: <input type="text" name="gender" placeholder="Gender" id="" <?php print "$Gender";?>><br>
Email Address: <input type="Email" name="email" placeholder="Email" id="g" <?php print "$Email";?>><br>
Password:<input type="Password" name="pwd" placeholder="Password" id="v" <?php print"$Password";?>><br>
<input type="submit" src="images/button(9).png" alt="Submit" id="q">
</form>
</div>
<?php include "Footer.php"; ?>
The PHP mysql lib is deprecated, you should consider using myslqi or php PDO instead.
Here is a tutorial
You should also be careful : $first_name and the other variables as they are not defined when you display the form, so you will get warnings.
Anyway, your problem is that this check is always false :
if(isset($_POST['submit'])){
The easiest (but not the best) way to correct that is to add a hidden input in your form :
<input type="hidden" name="hidden">
You have to quit the PHP script after telling the browser to redirect to another page:
header('Location: Donor.php');
exit;
(Besides SQL injection and some other problems.)

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