How to display succesfull message only when i submit the query? - php

It's a simple code but i can't understand where is my mistake. I want to display succesfull message under the form when i click the submit but the message stays there all the time. When i enter in the page where the form is the message is under the form. How to take it out only when the query is succesfull ?
<?php
$posted = false;
if(isset($_POST['add']))
{
$posted = true;
$email = $_POST['email'];
$name = $_POST['name'];
$rate = $_POST['rate'];
$comment = $_POST['comment'];
$dth = date("Y-m-d H:i:s");
$q = "INSERT INTO reviews(email, name, rate, comment, date_created) VALUES ('$email', '$name', '$rate', '$comment', '$dth')";
$k = mysqli_query($con,$q);
}
?>
<body>
<h1>Leave a review</h1>
<div class="error-conteiner">
</div>
<div class="clear"></div>
<form action="" method="post" class="form-content">
<div class="left">
<div class="field">
<label>E-mail <span class="required">*</span></label>
<input type="text" value="" name="email" class="required-field" data-validate="email"/>
</div>
<div class="clear"></div>
<div class="field">
<label>Name</label>
<input type="text" value="" name="name"/>
</div>
<div class="clear"></div>
<div class="field">
<label>Rate</label>
<select name="rate">
<option value=''>Choose rate</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
</div>
</div>
<div class="left">
<label>Comment <span class="required">*</span></label>
<textarea name="comment" class="comment required-field"></textarea>
</div>
<input type="submit" value="Send" class="btn" name="add" />
</form>
<?php
if($posted){
if($k)
echo "Thank you for your comment!";
else
die(mysqli_error());
}
?>
</body>
</html>

Maybe it is not professional and nice solution, but works well, if you make a query after the post with ex. $email and $name or other parameters. If the result is not empty, then you can put the results or just a simple message also into the output.

Replace
<?php
if($posted){
if($k)
echo "Thank you for your comment!";
else
die(mysqli_error());
}
?>
with
<?php
if($posted===true){
if($k) echo "Thank you for your comment!";
else die(mysqli_error());
}
?>

Maybe you have to put {} after your first if

Directly below:
$k = mysqli_query($con,$q);
add:
if(!$k) {
die(mysqli_error());
}
If the query wasn't executed, for whatever reason, show the error and stop.
You might consider adding a development mode variable or constant, because the mysqli_error() message is only valuable for the developer and the content is not for your users eyes. Anyway:
Replace:
<?php
if($posted){
if($k)
echo "Thank you for your comment!";
else
die(mysqli_error());
}
?>
with:
if($posted === true) {
echo 'Thank you for your comment!';
}
The mysql error is handled, where it occurs.
The success message is only displayed, when successfully send.
It's also possible to make a header redirection on success. But that depends, on what you like.
if($posted === true) {
header('Location: success-message-page.php');
exit;
}

Related

PHP:Update in MySQL database table sets blank values in the columns

I am retrieving values from the database into the form for update, on the press of the submit button, the values should get updated.
Here's the code:
PostUpdate.php:
<?php
session_start();
$username=$_SESSION['uname'];
$cn=mysqli_connect("localhost", "root", "", "testdb");
// Define variables and initialize with empty values
$course = $category = "";
$title = $descp = "";
// Processing form data when form is submitted
if(isset($_POST["pid"]) && !empty($_POST["pid"])){
// Get hidden input value
$pid = $_POST["pid"];
// Check input errors before inserting in database
if(empty($course) && empty($category) && empty($title) && empty($descp)){
// Prepare an update statement
$sql = "UPDATE posts SET course=?, category=?, title=?, descp=? WHERE pid=?";
if($stmt = mysqli_prepare($cn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ssssi", $param_course, $param_category, $param_title, $param_descp, $param_pid);
// Set parameters
$param_course = $course;
$param_category = $category;
$param_title = $title;
$param_descp = $descp;
$param_pid = $pid;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Records updated successfully. Redirect to landing page
header("location: CAposts.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($cn);
} else{
// Check existence of id parameter before processing further
if(isset($_GET["pid"]) && !empty(trim($_GET["pid"]))){
// Get URL parameter
$pid = trim($_GET["pid"]);
// Prepare a select statement
$sql = "SELECT * FROM posts WHERE pid = ?";
if($stmt = mysqli_prepare($cn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_pid);
// Set parameters
$param_pid = $pid;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
$result = mysqli_stmt_get_result($stmt);
if(mysqli_num_rows($result) == 1){
/* Fetch result row as an associative array. Since the result set contains only one row, we don't need to use while loop */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
// Retrieve individual field value
$pid = $row['pid'];
$uname = $row['uname'];
$course = $row['course'];
$category = $row['category'];
$pdate = $row['pdate'];
$title = $row['title'];
$descp = $row['descp'];
} else{
// URL doesn't contain valid id. Redirect to error page
header("location: CAposts.php");
exit();
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($cn);
} else{
// URL doesn't contain id parameter. Redirect to error page
header("location: CAposts.php");
exit();
}
}
?>
<html>
<head>
<title>IMEDTalks-Post-
<?php echo $title;?>
</title>
<link href="./css/bootstrap.min.css" rel="stylesheet" />
<script src="./scripts/jquery-3.3.1.min.js"></script>
<script src="./scripts/bootstrap.min.js"></script>
<style>
/* Make the image fully responsive */
.carousel-inner img {
width: 100%;
height: 30%;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2 class="text-center">Update Post</h2>
</div>
<p class="text-center">Please edit the input values and submit to update the post.</p>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group">
<div class="row">
<label class="col-form-label col-md-1 offset-3" for="course">Course:</label>
<div class="col-md-2">
<select name="course" class="form-control" required>
<option value="<?php echo $course;?>" selected>
<?php echo $course;?>
</option>
<option value="">Choose any:</option>
<option value="comp">Comp</option>
<option value="theo">Theory</option>
</select>
</div>
<label class="col-form-label col-md-1" for="category">Category:</label>
<div class="col-md-3">
<select name="category" class="form-control" required>
<option value="<?php echo $category;?>" selected>
<?php echo $category;?>
</option>
<option value="">Choose any:</option>
<option value="plang">Programming Language</option>
<option value="web">Web Technologies</option>
<option value="maths">Mathematics and Statistics</option>
<option value="others">Others</option>
</select>
</div>
</div>
</div>
<div class="form-group row">
<label for="title" class="col-form-label col-md-2">Title:
</label>
<div class="col-md-10">
<input type="text" class="form-control" value="<?php echo $title;?>" name="title" required>
</div>
</div>
<div class="form-group row">
<label for="desc" class="col-form-label col-md-12">Description:
</label>
<div class="col-md-12">
<textarea class="form-control" name="descp" rows="20" required><?php echo $descp;?></textarea>
</div>
</div>
<input type="hidden" name="pid" value="<?php echo $pid;?>" />
<div class="form-group row">
<div class="col-md-4 offset-4">
<a href="CAposts.php"><button type="button" name="cancel"
class="btn-lg btn-danger">Cancel</button></a>
</div>
<div class="col-md-4">
<button type="submit" name="update" class="btn-lg btn-success">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Here, i am using pid which is being bought from the previous page where the data is listed in table format, and on the click of a button there, that data/post gets loaded into the form for editing and updating the same using the pid(primary key in my database table)
Iam using bootstrap 4.
Problem i am facing:
The update operation is performed without any errors using the pid, but the values of course, category, title, description gets set to blank in database table after this update operation.
I can't figure out whats going wrong here.

How to redirect to another page(if field is set) or show error on same page(if field is empty) on clicking submit in php

I have 4 fields, when page loads I don't want any error to show up. But if fields are left empty and submit is clicked then I want to show errors.
I want my page to load first. Then when "submit" is clicked, it checks that whether any of the fields are not set, if so then show these errors and prevent the page from getting redirected to other page(Here "slots.php"), and if everything is okay then redirect the page.
This is the php code:
<?php
$error = "";
if($_POST){
if($_POST['parking_area']!="")
{$_SESSION['parking_area'] = $_POST['parking_area'];}
if($_POST['vehicle_no']!="")
{$_SESSION['vehicle_no'] = $_POST['vehicle_no'];}
if($_POST['time_from']!="")
{$_SESSION['time_from'] = $_POST['time_from'];}
if($_POST['time_to']!="")
{$_SESSION['time_to'] = $_POST['time_to'];}
if($_POST['parking_area'] == "select" || $_POST['parking_area'] == "" )
{$error .= "<p>Please select the parking area</p>";}
if(!$_POST['vehicle_no'])
{$error .= "<p>Please enter the vehicle number</p>";}
if(!$_POST['time_from'])
{$error .= "<p>Please enter the in time</p>";}
if(!$_POST['time_to'])
{$_error .= "<p>Please enter the out time</p>";}
if($error!=""){
$error = "<div class='error'>".$error."</div>";
}
}
?>
This is the html code:
<div><?php echo $error;?></div>
<div class="main-form">
<!--<div id="faltu"></div>-->
<!--action="slots.php"-->
<form method="POST" action="slots.php">
<div class="area main-form-components">
<select name="parking_area">
<option value="select">--Select--</option>
<option value="mahu-naka">Mahu Naka Parking</option>
<option value="collectorate">Collector Office Parking</option>
<option value="treasure-island">Treasure Island</option>
<option value="central-mall">Central Mall Parking</option>
</select>
</div>
<div class="time main-form-components">
<input type="time" name="time_from" value="09:30"> to
<input type="time" name="time_to" value="17:30">
</div>
<div class="vnumber main-form-components">
<input type="text" name="vehicle_no">
</div>
<!--
<div class="buttons">
<div id="prev-button"><i class="fas fa-arrow-left"></i> Prev.</div>
<div id="next-button">Next <i class="fas fa-arrow-right"></i></div>
</div>
-->
<div>
<input type="submit">
</div>
<!--<div class="buttons">
<button><i class="fas fa-arrow-left"></i> Prev.</button>
<button>Next <i class="fas fa-arrow-right"></i></button>
</div>-->
</form>
</div>
Edit: I know how I can do it with javascript, but I am looking for a way to do this without using javascript, only with php if possible.
This should work. I have both my html and php code in the same file as slots.php Once the values are posted we validate the value and if all values are there means we redirect to success page or we show error in same page.
<?php
$error = "";
if($_POST){
if($_POST['parking_area']!=""){
$_SESSION['parking_area'] = $_POST['parking_area'];
}
if($_POST['vehicle_no']!=""){
$_SESSION['vehicle_no'] = $_POST['vehicle_no'];
}
if($_POST['time_from']!=""){
$_SESSION['time_from'] = $_POST['time_from'];
}
if($_POST['time_to']!=""){
$_SESSION['time_to'] = $_POST['time_to'];
}
if($_POST['parking_area'] == "select" || $_POST['parking_area'] == "" ){
$error .= "<p>Please select the parking area</p>";
}
if(!$_POST['vehicle_no']){
$error .= "<p>Please enter the vehicle number</p>";
}
if(!$_POST['time_from']){
$error .= "<p>Please enter the in time</p>";
}
if(!$_POST['time_to']){
$_error .= "<p>Please enter the out time</p>";
}
if($error!=""){
$error = "<div class='error'>".$error."</div>";
}
else {
header('Location: success.php');
}
}
?>
I have added header location redirect if there is no error. Consider success.php is the page where we need to redirect the user if the values are set in the page.
<div>
<?php echo $error;?></div>
<div class="main-form">
<form method="POST" action="slots.php">
<div class="area main-form-components">
<select name="parking_area">
<option value="select">--Select--</option>
<option value="mahu-naka">Mahu Naka Parking</option>
<option value="collectorate">Collector Office Parking</option>
<option value="treasure-island">Treasure Island</option>
<option value="central-mall">Central Mall Parking</option>
</select>
</div>
<div class="time main-form-components">
<input type="time" name="time_from" value="09:30"> to
<input type="time" name="time_to" value="17:30">
</div>
<div class="vnumber main-form-components">
<input type="text" name="vehicle_no">
</div>
<div>
<input type="submit">
</div>
</form>
</div>
Should define ID or NAME tag for each input and then :
In this example for two textarea(a,b):
<script type="text/javascript">
function func()
{
var a=document.forms["Form"]["answer_a"].value;
var b=document.forms["Form"]["answer_b"].value;
if (a==null || a=="",b==null || b=="")
{
alert("Please Fill All Required Field");
return false;
}
}
</script>
<form method="post" name="Form" onsubmit="return func()" action="">
<textarea cols="30" rows="2" name="answer_a" id="a"></textarea>
<textarea cols="30" rows="2" name="answer_b" id="b"></textarea>
<input type="submit">
</form>

PHP - Validate if textbox has a value or not?

I want to validate if the textbox has a value or not. Right now what I have is a textbox that has a value but the output says it is empty here is it it is like nothing is being conditioned on the code please see me code, thank you
Full Code
-Here is the full code of my form please take a look thank you very much
<form>
<div class="row">
<form method="POST">
<div class="col-md-8">
<?php
$code = 'Code';
$code2 = 'PIN';
if(isset($_POST['btnSubcode'])) {
$lblCode = isset($_POST['lblQrTxt']) ? $_POST['lblQrTxt'] : '';
$code = $lblCode;
$code = explode(":",$code); // code = array("QR Code","444444444|123")
$code = explode("|",$code[1]); // code[1] = "444444444|123"
$code = trim($code[0]); // 444444444
$code2 = $lblCode;
$code2 = explode(":",$code2); // code = array("QR Code","444444444|123")
$code2 = explode("|",$code2[1]); // code[1] = "444444444|123"
$code2 = trim($code2[1]); // 123
}
?>
<div class="form-group">
<label class="form-control-label">code</label>
<input type="text" name="input" id="card-code" value='<?php echo $code ?>' class="form-control">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-control-label">pin</label>
<input type="text" id="card-pin" value='<?php echo $code2 ?>' class="form-control" maxlength="3">
</div>
<?php
if(isset($_POST['txtQrtxt']) && $_POST['txtQrtxt'] != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
<div class="caption">
<div class="jumbotron">
<input type="text" name='txtQrtxt' value='Hello World' class="form-control" >
<textarea class="form-control text-center" id="scanned-QR" name="lblQrTxt"></textarea><br><br><br>
</div>
</div>
</form>
<div class="form-group float-right">
<input value="Topup" class="btn btn-primary topup-button">
</div>
</div>
</div>
</form>
<?php
$txtCodeqr = isset($_POST['txtQrtxt']) ? $_POST['txtQrtxt'] : '';
if (!empty($txtCodeqr)) {
echo "Text";
} else {
echo "Empty Textbox";
}
?>
my textbox
<input type="text" name='txtQrtxt' value='Hello World' class="form-control" >
You might be over complicating it. It is pretty simple.
<?php
if(isset($_POST['txt']) && $_POST['txt'] != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
Additionally I would recommend you filter all input on post or get. Basically anything that gets information from a user.
Check here - http://php.net/manual/en/function.filter-input.php
<?php
$my_txt = filter_input(INPUT_POST, 'txt');
if(isset($my_txt) && $my_txt != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
Also you need to add a submit button between your form tags. Like this.
<input type="submit" value="Submit">
Also you should have only one closing tag for every opening tag. This is called valid HTML.
For example a valid form is like
<form method="post">
First name:<br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</form>
Ok I have made a simple php test file and tested it works. Your problem is:
You don't have a submit button. The $_POST will not be there if you do not submit a form first.
It would be easier to validate your textarea using javascript instead.
Here is my test file and it works:
<html>
<body>
<form method="POST">
<textarea name="txtQrtxt">
</textarea>
<input type="submit">
</form>
<?php
$var = $_POST['txtQrtxt'];
if (strlen($var)<=0) {
echo "Textarea empty";
} else {
echo "Textarea Okay";
}
?>
</body></html>

AMP form response not working in google cache

I created an AMP page for my website, all works fine on my desktop browser, tested and works fine on my mobile, if certain fields are empty or not valid, the submit-error correctly displays the error message, also, on successful submission it correctly displays the submit-success message.
When I submitted the page to Google to cache the amp page, I tested the form once again, this time it isn't displaying the error or success messages. But if the form submission is valid, it will send me an email but not display the success message.
Form html code:
<form action-xhr="posts/submit.php" method="POST" class="contactForm" target="_top">
<fieldset>
<div class="formFieldWrap">
<label class="field-title">Select a product:<span>(required)</span></label>
<div class="select-style full-bottom">
<select name="product">
<option selected="" disabled="">Select a Product</option>
<option value="product1">product 1</option>
<option value="product2">product 2</option>
</select>
</div>
</div>
<div class="formFieldWrap">
<label class="field-title">Full Name:<span>(required)</span></label>
<input type="text" name="fullname" value="" class="contactField" />
</div>
<div class="formFieldWrap">
<label class="field-title">Telephone: <span>(required)</span></label>
<input type="text" name="telephone" value="" class="contactField" />
<div class="formFieldWrap">
<label class="field-title">Email: <span>(required)</span>
</label>
<input type="text" name="email" value="" class="contactField" />
</div>
<input type="hidden" name="ps" value="amp_Homepage">
<div class="formSubmitButtonErrorsWrap contactFormButton">
<input type="submit" class="buttonWrap button bg-teal-dark contactSubmitButton" value="Start my claim" />
</div>
</fieldset>
<div submit-success>
<template type="amp-mustache">
<span class="center-text color-green-dark"><strong>Congratulations {{fullname}}!</strong> You have successfully submitted your claim. You can expect a telephone call from My Claim Solved just to confirm a few details.</span>
</template>
</div>
<div submit-error>
<template type="amp-mustache">
<span class="center-text color-red-light"><strong>Oops!</strong> {{message}}</span>
</template>
</div>
</form>
PHP page:
<?php
$source_origin = trim($_REQUEST['__amp_source_origin']);//Security
if($source_origin != "https://example.com"){
echo "Not allowed origin";
return;
}
header('AMP-Access-Control-Allow-Source-Origin: https://example.com');
header('Content-Type: application/json; charset=UTF-8;');
$start = microtime(true);
$con=mysqli_connect("myip","myuser","mypass","mydb");
$Product = mysqli_real_escape_string($con, $_REQUEST['product']);
$FullName = mysqli_real_escape_string($con, $_REQUEST['fullname']);$FullName = ltrim($FullName);$FullNameMail = mysqli_real_escape_string($con, $_REQUEST['fullname']);
$Telephone = mysqli_real_escape_string($con, $_REQUEST['telephone']);
$Email = mysqli_real_escape_string($con, $_REQUEST['email']);
$Provider = mysqli_real_escape_string($con, $_REQUEST['provider']);
$PageSource = mysqli_real_escape_string($con, $_REQUEST['ps']);
if($Product != 'product1' && $Product != 'product2'){
header('Status: 400', TRUE, 400);
echo json_encode(array('message'=>'You must select a product.'));
}elseif(empty($FullName) || strlen($FullName)<3) {
header('Status: 400', TRUE, 400);
echo json_encode(array('message'=>'You must enter your full name.'));
}elseif (empty($Telephone) || strlen($Telephone)<9) {
header('Status: 400', TRUE, 400);
echo json_encode(array('message'=>'You must enter a valid telephone number.'));
}elseif (!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
header('Status: 400', TRUE, 400);
echo json_encode(array('message'=>'You must enter a valid email address.'));
}else{
// Send Email
$To = "myemail#example.com";
$Message = "bla bla";
$Headers = "From: myemail#example.com";
mail($To, 'subject bla', $Message, $Headers);
echo json_encode(array("product"=>$Product,"fullname"=>$FullName,"telephone"=>$Telephone,"email"=>$IPAddress));
}
?>
just to let you know how it was fixed (thanks to ade for pointing me in the right direction), I amended the headers on the php page to the below:
header("access-control-allow-credentials:true");
header("access-control-allow-headers:Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token");
header("access-control-allow-methods:POST, GET, OPTIONS");
header("access-control-allow-origin:".$_SERVER['HTTP_ORIGIN']);
header("access-control-expose-headers:AMP-Access-Control-Allow-Source-Origin");
header("amp-access-control-allow-source-origin:https://".$_SERVER['HTTP_HOST']);
header("Content-Type: application/json");

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

Categories