The form is sent without validation: php mysql - php

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>

Related

My data is not sended to database through 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.

My php is showing validation errors but JS isnt

I am in the early stages of making a registration page for my website. However, the basic form I have created is being validated by javascript and php to ensure the right data will be entered. Even when the javascript is showing no errors and allowing the form to submit, the PHP errors are still being flagged and stopping it. below is the code for the php and html form. Any help will be greatly appreciated, these things are normally a lot easier than anticipated but its driving me crazy as it isnt showing any syntax errors just the errors that i have set up for the user.
The include files just have the mysql password and some basic functions for checking phone numbers.
Thanks in advance
HTML
<?php require_once("functions.inc"); ?>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="register.js"></script>
<link rel="stylesheet" href="form.css">
<title>A Form</title>
</head>
<body>
<form id="userForm" method="POST" action="register-process.php">
<div>
<fieldset>
<legend>Registration Information</legend>
<div id="errorDiv">
<?php
if (isset($_SESSION['error']) && isset($_SESSION['formAttempt'])){
unset($_SESSION['formAttempt']);
print "errors encountered<br>\n";
foreach ($_SESSION['error'] as $error) {
print $error . "<br>\n";
}//end foreach
} // end if
?>
</div>
<label for="fname">First Name:* </label>
<input type="text" id="fname" name="fname">
<span class="errorFeedback errorSpan" id="fnameError">First Name is required</span>
<br>
<label for="name">Last Name:* </label>
<input type="text" id="lname" name="lname">
<span class="errorFeedback errorSpan" id="lnameError">Last Name is required</span>
<br>
<label for="email">Email Address:* </label>
<input type="text" id="email" name="email">
<span class="errorFeedback errorSpan" id="emailError">Email is required</span>
<br>
<label for="password1">Password:* </label>
<input type="password" id="password1" name="password1">
<span class="errorFeedback errorSpan" id="password1Error">Password is required</span>
<br>
<label for="password2">Varify Password:* </label>
<input type="password" id="password2" name="password2">
<span class="errorFeedback errorSpan" id="password2Error">Password's do not match</span>
<br>
<label for="addr">Address: </label>
<input type="text" id="addr" name="addr">
<br>
<label for="city">City: </label>
<input type="text" id="city" name="city">
<br>
<label for="state">State: </label>
<select name="state" id="state">
<option></option>
<option value="AL">Alabama</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="FL">Florida</option>
<option value="IL">Illinois</option>
<option value="NJ">New Jersey</option>
<option value="NY">New York</option>
<option value="WI">Winconsin</option>
</select>
<br>
<label for="zip">ZIP: </label>
<input type="text" id="zip" name="zip">
<br>
<label for="phone">Phone Number: </label>
<input type="text" id="phone" name="phone">
<span class="errorFeedback errorSpan" id="phoneError">Format: xxx-xxx-xxxx</span>
<br>
<br>
<label for="work">Number Type:</label>
<input class="radioButton" type="radio" name="phoneType" id="work" value="work">
<label class="radioButton" for="work">Work</label>
<input class="radioButton" type="radio" name="phoneType" id="home" value="home">
<label class="radioButton" for="home">Home</label>
<span class="errorFeedback errorSpan phoneTypeError" id="phoneTypeError">Please Choose an option.</span>
<br>
<input type="submit" id="submit" name="submit">
</fieldset>
</div>
</form>
</body>
PHP register process.php
<?php
require_once('functions.inc');
//prevent access if they havent submitted the form!!
if (!isset($_POST['submit'])) {
die(header("location: register.php"));
}
$_SESSION['formAttempt'] = true;
if (isset($_SESSION['error'])) {
unset($_SESSION['error']);
}
$_SESSION['error'] = array();
$required = array("fname","lname", "email", "password1", "password2");
//check required fields!
foreach ($required as $requiredField) {
if (!isset($_POST[requiredField]) || $_POST[$requiredField] == "") {
$_SESSION['error'][] = $requiredField . " is required.";
}
}
if (!preg_match('/^[\w .]+$/',$_POST['fname'])) {
$_SESSION['error'][] = "Name must be letters and numbers only.";
}
if (!preg_match('/^[\w .]+$/',$_POST['lname'])) {
$_SESSION['error'][] = "Name must be letters and numbers only.";
}
if (isset($_POST['state']) && $_POST['state'] != "") {
if (!isValidState($_POST['state'])) {
$_SESSION['error'][] = "Please choose a valid state";
}
}
if (isset($_POST['zip']) && $_POST['zip'] != "") {
if (!isValidZip($_POST['zip'])) {
$_SESSION['error'][] = "ZIP code error";
}
}
if (isset($_POST['phone']) && $_POST['phone'] != "") {
if (!preg_match('/^[\d]+$/', $_POST['phone'])) {
$_SESSION['error'][] = "Phone numbner should be digits only.";
} else if (strlen($_POST['phone']) < 10 ) {
$_SESSION['error'] = "Phone number should be at least 10 digits.";
}
if (!isset($_POST['phoneType']) || $_POST['phoneType'] == "") {
$_SESSION['error'][] = "Please choose a phone type.";
} else {
$validPhoneTypes = array("work","home");
if (!in_array($_POST['phoneType'], $validPhoneTypes)) {
$_SESSION['error'][] = "Please choose a valid phone type";
}
}
}
if (!filter_var($_POST['email'],FILTER_VALIDATE_URL)) {
$_SESSION['error'][] = "Invalid e-mail address!";
}
if ($_POST['password1'] != $_POST['password2']) {
$_SESSION['error'] = "Passwords do not match";
}
//Final Disposition
if (count($_SESSION['error']) > 0) {
die (header("Location: register.php"));
} else {
if (registerUser($_POST)) {
unset($_SESSION['formAttempt']);
die(header("Location: success.php"));
} else {
error_log("problem registering user: {$_POST['email']}");
$_SESSION['error'][] = "Problem registering account";
die(header("Location: register.php"));
}
}
The extension is the rest of the process php file, i have commented where the errors are coming from.... Thanks Again..
if (count($_SESSION['error']) > 0) {
die (header("Location: register.php"));
} else {
if (registerUser($_POST)) {
unset($_SESSION['formAttempt']);
die(header("Location: success.php"));
} else {
error_log("problem registering user: {$_POST['email']}"); // THIS IS WHERE THE ERROR IS COMNING FROM
$_SESSION['error'][] = "Problem registering account";
die(header("Location: register.php"));
}
}
function registerUser($userData) {
$mysqli = new mysqli(DBHOST,DBUSER,DBPASS,DB);
if ($mysqli->connect_errno) {
error_log("Cannot connect to MySQL: " . $mysqli->connect_error);
return false;
}
$email = $mysqli->real_escape_string($_POST['email']);
//Check for an existing user
$findUser = "SELECT id from Customer where email = '{$email}'";
$findResult = $mysqli->query($findUser);
$findRow = $findResult->fetch_assoc();
if (isset($findRow['id']) && $findRow['id'] != "") {
$_SESSION['error'][] = "A user with that email already exists";
return false;
}
$lastname = $mysqli->real_escape_string($_POST['lname']);
$firstname = $mysqli->real_escape_string($_POST['fname']);
$cryptedPassword = crypt($_POST['password1']);
$password = $mysqli->real_escape_string($cryptedPassword);
if (isset($_POST['addr'])) {
$street = $mysqli->real_escape_string($_POST['addr']);
} else {
$street = "";
}
if (isset($_POST['city'])) {
$city = $mysqli->real_escape_string($_POST['city']);
} else {
$city = "";
}
if (isset($_POST['state'])) {
$state = $mysqli->real_escape_string($_POST['state']);
} else {
$state = "";
}
if (isset($_POST['zip'])) {
$zip = $mysqli->real_escape_string($_POST['zip']);
} else {
$zip = "";
}
if (isset($_POST['phone'])) {
$phone = $mysqli->real_escape_string($_POST['phone']);
} else {
$phone = "";
}
if (isset($_POST['phoneType'])) {
$phoneType = $mysqli->real_escape_string($_POST['phoneType']);
} else {
$phoneType = "";
}
$query = "INSERT INTO Customer (email,create_date,password,last_name,first_name,street,city,state,zip,phone,phone_type) " . "VALUES ('{$email}',NOW(),'{$password}','{$lastname}','{$firstname}'" . ",'{$street}','{$city}','{$zip}','{$phone}','{$phoneType}')";
if ($mysqli->query($query)) {
$id = $mysqli->insert_id;
error_log("inserted {$email} as ID {$id}");
return true;
} else {
error_log("Problem inserting {$query}");
$_SESSION['error'][] = "HERE"; // THIS IS WHERE THE ERROR IS COMNING FROM
return false;
}
}
?>
Your query has a bug in it. Column count isn't the same as value count. You forgot to pass in $state.
$query = "INSERT INTO Customer (email,create_date,password,last_name,first_name,street,city,state,zip,phone,phone_type) " . "VALUES ('{$email}',NOW(),'{$password}','{$lastname}','{$firstname}'" . ",'{$street}','{$city}','{$state}', '{$zip}','{$phone}','{$phoneType}')";
if ($mysqli->query($query)) {
$id = $mysqli->insert_id;
error_log("inserted {$email} as ID {$id}");
return true;
} else {
error_log("Problem inserting {$query}");
error_log("Problem inserting {$mysqli->error}"); // log the error
$_SESSION['error'][] = "HERE"; // THIS IS WHERE THE ERROR IS COMNING FROM
return false;
}

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

How to add session to an HTML log in form

I'm working on an HTML form, which is connected to MySQL database. Database is updating with new data every time, when I reload the page and also when a failed submit occur.
This is my code, Anyone please help me to add session to this page and please give me a solution
<body>
<?php
// define variables and set to empty values
$email_id = $first_name = $last_name = $district = $city = $address = $mobile_no = $password = "";
$email_idErr = $first_nameErr = $last_nameErr = $districtErr = $cityErr = $addressErr = $mobile_noErr = $passwordErr = "";
?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//First name validation
if(empty($_POST["first_name"]))
{$first_nameErr="First name is required";}
else
{$first_name = test_input($_POST["first_name"]);
//checking name formats
if(!preg_match("/^[a-zA-Z]*$/",$first_name))
{$first_nameErr="Only letters and white spaces allowed";}
}
//Second name validation
if(empty($_POST["last_name"]))
{$last_nameErr="Last name is required";}
else
{$last_name = test_input($_POST["last_name"]);
//checking name formats
if(!preg_match("/^[a-zA-Z]*$/",$last_name))
{$last_nameErr="Only letters and white spaces allowed";}
}
//E-mail validation
if(empty($_POST["email_id"]))
{$email_idErr="E-mail id is required";}
else
{$email_id = test_input($_POST["email_id"]);
//checking email format
if(!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email_id))
{$email_idErr="Invalid email format";}
}
//District is required
if(empty($_POST["district"]))
{ $districtErr="District is required";}
else
{ $district = test_input($_POST["district"]);
if(!preg_match("/^[a-zA-Z]*$/",$district))
{$districtErr="Only letters and white spaces allowed";}
}
$city = test_input($_POST["city"]);
$address = test_input($_POST["address"]);
//Mobile number validation
if(empty($_POST["mobile_no"]))
{$mobile_noErr="Mobile number is required";}
else
{$mobile_no = test_input($_POST["mobile_no"]);
if(!preg_match("/^[0-9]*$/",$mobile_no))
{$mobile_noErr="Invalid Mobile number";}
}
//Password validation
if(empty($_POST["password"]))
{$passwordErr="Password is required";}
else
{ $password = test_input($_POST["password"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php
$con=mysqli_connect("localhost","root","","ashlyn");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{echo "Connection Established";}
$sql="INSERT INTO user_details (email_id, first_name, last_name, district, city, address, mobile_no, password)
VALUES ('$email_id', '$first_name', '$last_name', '$district', '$city', '$address', '$mobile_no', '$password')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "You are successfully registered..";
mysqli_close($con);
?>
<section class="container">
<div class="login">
<h1>User Login Page</h1>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);>">
<p><input type="text" name="first_name" value="" placeholder="First Name"><span class="error">* <?php echo $first_nameErr;?></span></p>
<p><input type="text" name="last_name" value="" placeholder="Last Name"> <span class="error">* <?php echo $last_nameErr;?></span>
</p>
<p><input type="text" name="email_id" value="" placeholder="Email"><span class="error">* <?php echo $email_idErr;?></span>
</p>
<p><input type="text" name="district" value="" placeholder="District"><span class="error">* <?php echo $districtErr;?></span></p>
<p><input type="text" name="city" value="" placeholder="City">
</p>
<p><input type="text" name="address" value="" placeholder="Address">
</p>
<p><input type="text" name="mobile_no" value="" placeholder="Mobile Number"> <span class="error">* <?php echo $mobile_noErr;?></span>
</p>
<p><input type="password" name="password" value="" placeholder="Password"> <span class="error">* <?php echo $passwordErr;?></span>
</p>
<p class="submit"><input type="submit" name="submit" value="Submit"></p>
</form>
what you need is
<?php session_start();
on the first line bevor any output
https://stackoverflow.com/a/8084900/1792420

Categories