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 */
}
Related
I would like to display error checking next to the input field. Currently, errors are displayed at the top of the page.
Maybe there is some way to check for input errors?
I could not find a similar example where html and php code are separated into different files
Or my code is completely wrong.
index.php
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>testpage</title>
</head>
<body>
<?php
require('process.php');
?>
<h1>Form</h1>
<form method="post" action="">
<div> Date : <input type="date" name="date"/><br />
</div>
<div>
<label>Start:</label>
<select name="starttime" style="margin-right:15px" >
<option value="09:00:00">09:00</option>
<option value="17:00:00">17:00</option>
</select>
<label>End:</label>
<select name="endtime">
<option value="18:00:00">18:00</option>
</select>
<br>
</div>
<div>
Name : <input type="text" name="user_name" placeholder="Name" /><br />
</div>
Mail : <input type="email" name="user_email" placeholder="Mail" /><br />
Message : <textarea name="user_text"></textarea><br />
<input type="submit" value="Send" />
</form>
<h3 class=" txt_center">DB Output <span id="curdate">
<?php require('calendar.php');
?>
<!-- <script type="text/javascript" src="js/time-select.js"></script> -->
</body>
</html>
process.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$u_date = filter_var($_POST["date"]);
$u_starttime = $_POST["starttime"];
$u_endtime = $_POST["endtime"];
$u_name = filter_var($_POST["user_name"]);
$u_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
$u_text = filter_var($_POST["user_text"]);
$error = array();
if (empty($u_date)){
$error['date'] = 'Date is empty!';
}
elseif ( $u_starttime > $u_endtime ){
echo "*Incorrect time";
}
elseif (empty($u_name)){
echo "Name is empty.";
}
else{
require_once('db-connect.php');
$statement = $mysqli->prepare("INSERT INTO users_data (date, start_time, end_time, user_name, user_email, user_message) VALUES(?, ?, ?, ?, ?, ?)");
$statement->bind_param('ssssss', $u_date, $u_starttime, $u_endtime, $u_name, $u_email, $u_text);
if($statement->execute()){
print "Hello, " . $u_name . "!, request is complete!";
}else{
print $mysqli->error;
}
}
}
?>
You can add the 'required' attribute to <input> elements, which get validated on form submission. E.g. <input type="date" name="date" required/> eliminating the necessity to write code for error output.
EDIT: here you can see how the warning is shown
Also, the validation
elseif ( $u_starttime > $u_endtime ){
echo "*Incorrect time";
}
is not required, since the user's choices already force starttime < endtime.
Cheers
Here is an example for setting date validation next to your date input fields.
in process.php:
` $errordate="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$u_date = filter_var($_POST["date"]);
if (empty($u_date)){
$errordate= 'Date is empty!';
}}
and in your index.php:
<input type="date" name="date"/> * <?php echo "<p style='color:red;'>".$errordate . "</p>"; ?>
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.
I have an assignment that calls for data entries from a php form to be stored in a plain text file on the same web server. I created the php form page and the plain text file but I am unsure how to connect the two. I've searched the internet and tried multiple ways for about two hours now and no dice. The data entries have to accumulate in the plain text file too (1st person submits, and a 2nd person submitting can see 1st person's submission and so on).
I didn't add any of the code I've tried to the plain text file because none of them were working and I wanted to (in theory) simplify the process of not having to try and fix the code. I know that the plain text file needs some sort of code to retrieve the code from the php form but unsure what to try at this point. And yes I wrote permissions for the plain text file to be writable via FileZilla.
Here's my php form code:
<!DOCTYPE HTML>
<html>
<head>
<title>Roy Feedback Form Assignment 7</title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $commentErr = $likesErr = $howErr = $rateErr = "";
$name = $email = $comment = $likes = $how = $rate = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
if (empty($_POST["comment"])) {
$commentErr = "Comments are required";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["likes"])) {
$likesErr = "Things you liked is required";
} else {
$likes = test_input($_POST["likes"]);
}
if (empty($_POST["how"])) {
$howErr = "How you got to our site is required";
} else {
$how = test_input($_POST["how"]);
}
if (empty($_POST["rate"])) {
$rateErr = "Rating our site is required";
} else {
$rate = test_input($_POST["rate"]);
}
}
function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Roy Feedback Form Assignment 7</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<span class="error">* <?php echo $commentErr;?></span>
<br><br>
Things you liked:
<input type="radio" name="likes" value="Site design">Site design
<input type="radio" name="likes" value="Links">Links
<input type="radio" name="likes" value="Ease of use">Ease of use
<input type="radio" name="likes" value="Images">Images
<input type="radio" name="likes" value="Source code">Source code
<span class="error">* <?php echo $likesErr;?></span>
<br><br>
How you got to our site:
<input type="radio" name="how" value="Search engine">Search engine
<input type="radio" name="how" value="Links from another site">Links from another site
<input type="radio" name="how" value="Deitel.com website">Deitel.com website
<input type="radio" name="how" value="Reference from a book">Reference from a book
<input type="radio" name="how" value="Other">Other
<span class="error">* <?php echo $howErr;?></span>
<br><br>
Rate our site:
<select name="rate">
<option value="">- Please Select -</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>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<span class="error">* <?php echo $rateErr;?></span>
<br/><br/>
<input type="submit" name="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>
And here's the plain text file code:
<!DOCTYPE html>
<html>
<head>
<title>Roy Feedback Results Assignment 7</title>
</head>
<body>
</body>
</html>
Update 1
So I'm still having issues (sorry, I know it's like trying to teach PHP to a grapefruit). So when I use the following code nothing happens on the plain text page (as in the data isn't stored where I tell it to be):
function file_write($data, $feedback_results_html_only){
if(is_readable($feedback_results_html_only)){
if(is_string($data)){
return file_put_contents($feedback_results_html_only, $data, FILE_APPEND | LOCK_EX);//this appends the new data to the file and locks it while doing so to prevent multiple access to thje file at the same time.
}//return an error message if the data isnt a string
}//return an error message if the file doesnt exist or isnt readable
}
However when I use the following code it at least places the "John Smith" name into the file (which is the first time I actually got it to somewhat work, hooray coding!):
<?php
$file = 'feedback_results_html_only.php';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>
Also I am aware that I didn't use the ".php" on the "feedback_results_html_only" in the first example of code (in update 1) because it created an error. Could I possibly try something like the second example (in update 1) instead to make it work?
$file = 'feedback_results_html_only.php'
You are looking for file_put_contents(). Simply collect the data and write it to your file. Here is the refined code:
PS: You could consider starting with the php code first :-)
<?php
// define variables and set to empty values
$nameErr = '';
$emailErr = '';
$commentErr = '';
$likesErr = '';
$howErr = '';
$rateErr = '';
$name = '';
$email = '';
$comment = '';
$likes = '';
$how = '';
$rate = '';
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
if (empty($_POST["comment"])) {
$commentErr = "Comments are required";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["likes"])) {
$likesErr = "Things you liked is required";
} else {
$likes = test_input($_POST["likes"]);
}
if (empty($_POST["how"])) {
$howErr = "How you got to our site is required";
} else {
$how = test_input($_POST["how"]);
}
if (empty($_POST["rate"])) {
$rateErr = "Rating our site is required";
} else {
$rate = test_input($_POST["rate"]);
}
}
function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//concatenate the data, then format and validate it then use this function to write it to your plain text file
function file_write($data, $pathtoplaintxtfile){
if(is_string($data)){
return file_put_contents($pathtoplaintxtfile, $data, FILE_APPEND | LOCK_EX);//this appends the new data to the file and locks it while doing so to prevent multiple access to thje file at the same time.
}//return an error message if the data isnt a string
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Roy Feedback Form Assignment 7</title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>Roy Feedback Form Assignment 7</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<span class="error">* <?php echo $commentErr;?></span>
<br><br>
Things you liked:
<input type="radio" name="likes" value="Site design">Site design
<input type="radio" name="likes" value="Links">Links
<input type="radio" name="likes" value="Ease of use">Ease of use
<input type="radio" name="likes" value="Images">Images
<input type="radio" name="likes" value="Source code">Source code
<span class="error">* <?php echo $likesErr;?></span>
<br><br>
How you got to our site:
<input type="radio" name="how" value="Search engine">Search engine
<input type="radio" name="how" value="Links from another site">Links from another site
<input type="radio" name="how" value="Deitel.com website">Deitel.com website
<input type="radio" name="how" value="Reference from a book">Reference from a book
<input type="radio" name="how" value="Other">Other
<span class="error">* <?php echo $howErr;?></span>
<br><br>
Rate our site:
<select name="rate">
<option value="">- Please Select -</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>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<span class="error">* <?php echo $rateErr;?></span>
<br/><br/>
<input type="submit" name="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>
EDIT: file_put_contents() automaticly creates a file if it doesnt exist, remove is_readable file check.
EDIT: Usage -
$data = $name.$email.$comment.$likes.$how.$rate.
'This is just test data. If no other data is visible, then you didnt fill them out';
file_write($data, 'feedback_results_html_only.php')
Use file_put_contets
$relative_or_absolute_path = '../'; //relative folder up
$ext = '.txt'; //file can be with no extension at all or even *.php
$filename = 'plain_log';
$contents = '';
foreach($users as $user){
$contents .= $user . '\n'; //a newline
}
//execute
file_put_contents($relative_or_absolute_path.$filename.$ext, $contents, FILE_APPEND);
//FILE_APPEND is an optional flag // otherwise it will rewrite
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;
}
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>