I am trying to create error messages if certain conditions aren't met. So the user fills out a form and if a field is empty or doesn't pass my validation it returns the error message.
This is the form:
if (isset($_POST)) {
if (checkEmail($email) == TRUE && $name != NULL && $surName != NULL) {
mysql_query( "INSERT INTO USR_INFO (NAME, MAIL, SURNAME)
VALUES ('$name', '$email','$surName') ") or die(mysql_error());
header('Location: thanks.php');
}
else {
echo'<form action="<?php echo $_SERVER[\'PHP_SELF\']; ?>" method="POST">
<label for="name">First Name</label>
<input type="text" name="name" id="name" value="' .$_POST['name'].'" />
<span class="required">*</span>
<label for="surName">Last Name</label>
<input type="text" name="surName" id="surName" value="' .$_POST['surName']. '" />
<span class="required">*</span>
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#domain.com" value="' .$_POST['email']. '" />
<span class="required">*</span>
<input type="submit" name="submit" id="submit">
</form>';
}
} else {
echo'<form action="<?php echo $_SERVER[\'PHP_SELF\']; ?>" method="POST">
<label for="name">First Name</label>
<input type="text" name="name" id="name" value="" />
<span class="required">*</span>
<label for="surName">Last Name</label>
<input type="text" name="surName" id="surName" value="" />
<span class="required">*</span>
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#domain.com" value="" />
<span class="required">*</span>
<input type="submit" name="submit" id="submit">
</form>';
}
So what I tried is adding an array to display the error messages like so:
$errorMessage = array();
And add this to the html form field with the proper message:
$error[] = "Error Message";
Now what I am stuck with is that I want to have the error show only if a user doesn't meet the conditions
if ($name == NULL) {$error[] = "Error Message";}
if ($surName == NULL) {$error[] = "Error Message 2";}
if (checkEmail($email) == FALSE || NULL) {$error[] = "Error Message 3";}
But I can't make it work. When I tried to implement this logic it will parse the page fine and the validation works as well but the error messages wont show up if I leave a required field blank. My guess is that I didn't loop through it properly.
Help is much appreciated!
EDIT:
I tried the answer that was posted by Frosty Z and this is what I have at the moment:
if (isset($_POST)) {
$errorMessage = array();
if ($name == '') { $errors[] = "Input name please." }
if ($surName == '') { $errors[] = "Input last name please." }
if (!checkEmail($email)) { $errors[] = "Email address not valid." }
if (count($error) == 0) {
mysql_query( "INSERT INTO USR_INFO (NAME, MAIL, SURNAME)
VALUES ('$name', '$email', '$surName') ") or die(mysql_error());
header('Location: thanks.php');
exit;
else {
if (count($errors) > 0)
echo "<p>Sorry, there are problems with the information you have provided:</p>";
foreach($errors as $error)
echo '<p class="error">'.$error.'</p>';
echo'<form action="<?php echo $_SERVER[\'PHP_SELF\']; ?>" method="POST">
<label for="name">Name</label>
<input type="text" name="name" id="name" value="' .$_POST['name'].'" />
<span class="required">*</span>
<label for="surName">Last name</label>
<input type="text" name="surName" id="surName" value="' .$_POST['surName']. '" />
<span class="required">*</span>
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#domain.com" value="' .$_POST['email']. '" />
<span class="required">*</span>
<input type="submit" name="submit" id="submit">
</form>';
}
} else {
echo'<form action="<?php echo $_SERVER[\'PHP_SELF\']; ?>" method="POST">
<label for="name">Name</label>
<input type="text" name="name" id="name" value="" />
<span class="required">*</span>
<label for="surName">Achternaam</label>
<input type="text" name="surName" id="surName" value="" />
<span class="required">*</span>
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#domain.com" value="" />
<span class="required">*</span>
<input type="submit" name="submit" id="submit">
</form>';
}
With this my page won't be parsed. I have error reporting on but it doesn't show anything besides a
Internal server error 500
in my console log(Firebug)
Here is some rewriting of your work with a minimal handling of error messages.
BTW, you should consider adopting a decent PHP framework which will help you to handle a lot of common development tasks.
$name = '';
$surName = '';
$email = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = $_POST['name'];
$surName = $_POST['surName'];
$email = $_POST['email'];
$errors = array();
if ($name == '') { $errors[] = "Please type your name."; }
if ($surName == '') { $errors[] = "Please type your surname."; }
if (!checkEmail($email)) { $errors[] = "Wrong email format."; }
if (count($errors) == 0) {
// tip: use PDO or mysqli functions instead of mysql ones to bind variables.
// currently there is a risk of SQL injection here
mysql_query("INSERT INTO USR_INFO (NAME, MAIL, SURNAME)
VALUES ('$name', '$email','$surName') ") or die(mysql_error());
header('Location: thanks.php');
exit;
}
}
if (count($errors) > 0)
echo '<p>Sorry, there are problems with the information you have provided:</p>';
foreach($errors as $error)
echo '<p class="error">'.$error.'</p>';
echo '<form action="'.$_SERVER['PHP_SELF'].'" method="POST">
<label for="name">First Name</label>
<input type="text" name="name" id="name" value="'.htmlspecialchars($name).'" />
<span class="required">*</span>
<label for="surName">Last Name</label>
<input type="text" name="surName" id="surName" value="'.htmlspecialchars($surName).'" />
<span class="required">*</span>
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#domain.com" value="'.htmlspecialchars($email).'" />
<span class="required">*</span>
<input type="submit" name="submit" id="submit">
</form>';
Related
The landing page has form but it is not submitting and not redirecting to the next page.After submitting the form, it stays on the same page.
It was alright and was working before but I cant figure out where is the problem.
Code in formPage.php is below:
<form action="insert.php" enctype="multipart/form-data" class="contact_form" method="post" name="htmlform" >
<input class="frm-input" name="name" type="text" size="30" maxlength="50" placeholder="Enter Name" required="required" />
<input class="frm-input" name="email" type="text" size="30" maxlength="80" placeholder="Enter Email" required="required"/>
<input class="frm-input" name="jobtype" type="text" size="30" maxlength="30" placeholder="Job Type" required="required"/>
<input class="frm-input" name="ent_type" type="text" size="30" maxlength="80" placeholder="Entity Type" required="required"/>
<input class="frm-input" name="tas_out" type="text" size="30" maxlength="80" placeholder="Task Outline" required="required"/>
<input class="frm-input" name="l_st" type="text" size="30" maxlength="80" placeholder="Logo style of interest (optional)" />
<textarea required="required" class="frm-input frm-txtarea" name="message" placeholder="Task Description!!" maxlength="1000" cols="25" rows="6" ></textarea>
<input style="float: left;" type="file" name="image" size="66"/>
<input type="submit" class="btn btn-success btn-lg" name="submitt" value="submit" style="float: right" />
</form>
In this file I am trying to get the form information and storing them in database.But this page is not loading after the form submission.
Code in insert.php is below:
<?php
/*
$name = "";
$text = "";
$post = "";
*/
//echo $name;
if (isset($_POST['submitt']))
{
$name = $_POST["name"];
$mail = $_POST["email"];
$j_type = $_POST["jobtype"];
$e_type = $_POST["ent_type"];
$task = $_POST["tas_out"];
$l_st = $_POST["l_st"];
$task_des = $_POST["message"];
$image_name=$_FILES['image']['name'];
$image_type=$_FILES['image']['type'];
$image_size=$_FILES['image']['size'];
$image_temp=$_FILES['image']['tmp_name'];
//$date = date(m-d-y);
echo $name;
echo $mail;
echo $j_type;
echo $e_type;
echo $task;
echo $l_st;
echo $task_des;
if ($image_type=='image/jpeg' || $image_type=='image/png' || $image_type=='image/gif') {
move_uploaded_file($image_temp, "img/$image_name");
}
$connection=mysqli_connect("localhost", "root", "","com");
$query="insert into details (name, mail, j_type, e_type, task_outline, l_style, task_desc, image) values('".$name."','".$mail."','".$j_type."','".$e_type."','".$task."','".$l_st."','".$task_des."','".$image_name."')";
if(mysqli_query($connection,$query)){
//include('test.php');
echo '<h2>Data submitted successfully!!</h2>';
header("refresh:1; url=login.php");
//echo 'Back';
}else{
echo "Data not Submitted!";
# code...
}
}
echo "Data not Submitted!";
?>
echo "Data not Submitted!"; // put this line inside the last bracket
Sorry it was my fault,there was a typo mistake in the form action.Everything else is fine.
I was wondering if there was a way to to check if html text inputs are empty, and if so, execute a certain PHP code, which I will provide.
HTML
<input name="name" type="text" class="form-control form-control-lg" id="exampleInputName2" placeholder="your name" maxlength="36" value="<?php echo $name; ?>">
<input style="margin-top: 10px;" name="email" type="text" class="form-control form-control-lg" id="exampleInputEmail2" placeholder="your email" maxlength="36" value="<?php echo $email; ?>">
<button name="mySubmitBtn" type="submit" class="btn btn-default btn-md">subscribe</button>
PHP
if(!isset(['name']) || !isset(['email']) == 0){
$msg_to_user = '<h1>Fill out the forms</h1>';
}
I was wondering if:
My PHP code is correct syntax, which I believe it's not
Is it possible to check if an input is empty, and if it is empty,
execute a PHP code (specifically '$msg_to_user')
It is possible to tweak my code so that when the user clicks the
submit button, and the fields are BOTH empty, to have the
$msg_to_user code execute
Thank you in advance!
You should use isset check on array - $_POST or $_GET according to your HTML form method.
It should be:
<form method="POST">
<input name="name" type="text" class="form-control form-control-lg" id="exampleInputName2" placeholder="your name" maxlength="36" value="">
<input style="margin-top: 10px;" name="email" type="text" class="form-control form-control-lg" id="exampleInputEmail2" placeholder="your email" maxlength="36" value="">
<button name="mySubmitBtn" type="submit" class="btn btn-default btn-md">subscribe</button>
</form>
PHP:
if (!isset($_POST['name']) || !isset($_POST['email']))
{
$msg_to_user = '<h1>Fill out the forms</h1>';
} else {
// process your results
}
I guess, I have answered questions A and B. What about question C - it's up to your architecture. For example, if you want to post form from page to itself (I mean index.php file has a form with action='index.php' or empty action), then you can do it this way (just an example approach, definitely not the best):
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (!isset($_POST['name']) || !isset($_POST['email']))
{
$msg_to_user = '<h1>Fill out the forms</h1>';
} else {
// do something in database
if ($doSomethingInDatabaseSuccess)
$msg_to_user = '<h1>Succesffully saved!</h1>'; // really? h1? :)
else
$msg_to_user = '<h1>Something went wrong!</h1>';
} else {
$msg_to_user = '';
}
<form method="POST">
<input name="name" type="text" class="form-control form-control-lg" id="exampleInputName2" placeholder="your name" maxlength="36" value="">
<input style="margin-top: 10px;" name="email" type="text" class="form-control form-control-lg" id="exampleInputEmail2" placeholder="your email" maxlength="36" value="">
<button name="mySubmitBtn" type="submit" class="btn btn-default btn-md">subscribe</button>
</form>
<p class="result"><?php echo($msg_to_user); ?></p>
A. No your syntax is off.
B. Yes
C. Yes, first you need to give your button a name property, so that it can be picked up by PHP. You also need to assign the $email and $name variables with a $_POST variable.
HTML
<input type="text" name="name" class="form-control" id="exampleInputName2" placeholder="your name" maxlength="36" value="<?php echo $name; ?>">
<input type="email" style="margin-top: 10px;" name="email" class="form-control" id="exampleInputEmail2" placeholder="your email" maxlength="36" value="<?php echo $email; ?>">
<input type="submit" name="mySubmitBtn" class="btn btn-default btn-md" value="subscribe">
PHP
//check to see if the submit button is pressed
if(isset($_POST['mySubmitBtn'])){
//assign the variables from the content of the input form
$email = $_POST['email'];
$name = $_POST['name'];
//check if name is empty
if(!isset($name) || trim($name) ==''){
$errorMsg = "You must enter a name";
return;
}
//check if email is empty
if(!isset($email) || trim($email) ==''){
$errorMsg = "You must enter an email";
return;
}
//do something else
I have an rsvp form that I am trying to send the value of a radio button but unsure of the php for it, my code is as follows:
<div class="form-group">
<input type="text" name="name" id="name" size="30" value="" placeholder="Name(s)" class="text-input form-control" />
<label class="error" for="name" id="name_error">Name is required.</label>
</div>
<div class="form-group">
<input type="radio" name="response" id="response_accepted" value="accepted" checked="checked" > Will be there
<input type="radio" name="response" id="response_declined" value="declined"> Won't make it
<label class="error" for="response" id="name_error">Please select an option</label>
</div>
<div class="form-group">
<input type="text" name="guests" id="guests" size="30" value="" placeholder="No. of guests attending" class="text-input form-control" />
<label class="error" for="guests" id="guests_error">No. of guests is required.</label>
</div>
but i'm not sure of the php that collects the value of the radio button but have got the other fields to pass the data using:
<?php
if ((isset($_POST['name'])) && (strlen(trim($_POST['name'])) > 0)) {
$name = stripslashes(strip_tags($_POST['name']));
} else {$name = 'No name entered';}
if ((isset($_POST['guests'])) && (strlen(trim($_POST['guests'])) > 0)) {
$guests = stripslashes(strip_tags($_POST['guests']));
} else {$guests = 'No # of guests entered';}
?>
It will process in the same way as the other, the only difference is that you already know its value, so you will need to
if ((isset($_POST['response'])) && ($_POST['response'] == 'accepted' ) {
$response = 'Accepted';
} else {$response= 'Not Accepted';}
This code will help you
$response = $_POST['response'] ;
if(isset($response) && $resonse == "accepted" )){
echo "Accepted" ;
}
else{ echo "Declined" ; }
Trying to post a simple form to my database but can't get it to work. I have PHP and MySQL activated through XAMPP. The database "E-mail list" is set up with the table "Players".
PHP code:
<?php
$mysqli = new mysqli('localhost', 'root', '', 'E-mail list');
if(isset($_POST['save']))
{
$name = $mysqli->real_escape_string($_POST['name']);
$email = $mysqli->real_escape_string($_POST['email']);
$phone = $mysqli->real_escape_string($_POST['phone']);
$other = $mysqli->real_escape_string($_POST['other']);
$query = 'INSERT INTO Players (
name,
email,
phone,
other
)
VALUES ('.$name.', "'.$email.'", "'.$phone.'","'.$other.'")';
if ($mysqli->query($query))
{
echo 'Data Saved Successfully.';
}
else
{
echo 'Cannot save data.';
}}
?>
And the form:
<form id="myForm" method="post">>
<div data-role="fieldcontain">
<label for="name">Please enter your name:</label>
<input type="text" name="name" id="name" class="required" value="" autocomplete="off" />
<label for="email">Please enter your e-mail:</label>
<input type="text" name="email" id="email" value="" class="required" autocomplete="off" />
<label for="phone">Please enter your phone number:</label>
<input type="number" name="phone" id="phone" value="" class="required" autocomplete="off" />
<br><br>
<label for="other">Other comments</label>
<textarea name="other" id="other" autocomplete="off" placeholder="Anything else you'd like to add?">
</textarea>
</form>
<p><strong id="error"></strong></p>
<br><br>
<input type="button" id="save" name="save" value="Submit Form" />
<p id="response"></p>
I did some changes in your codes both PHP and HTML Parts.,
For PHP :
<?php
$mysqli = new mysqli('localhost', 'root', '', 'E-mail list');
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if(isset($_POST['save']))
{
$name = $mysqli->real_escape_string($_POST['name']);
$email = $mysqli->real_escape_string($_POST['email']);
$phone = $mysqli->real_escape_string($_POST['phone']);
$other = $mysqli->real_escape_string($_POST['other']);
$query = "INSERT INTO Players (`name`,`email`,`phone`,`other`) VALUES ('".$name."','".$email."','".$phone."','".$other."')";
if($mysqli->query($query))
{
echo 'Data Saved Successfully.';
}
else
{
echo 'Cannot save data.';
}
}
?>
For HTML :
<form id="myForm" method="post" action="">
<div data-role="fieldcontain">
<label for="name">Please enter your name:</label>
<input type="text" name="name" id="name" class="required" value="" autocomplete="off" /><br />
<label for="email">Please enter your e-mail:</label>
<input type="text" name="email" id="email" value="" class="required" autocomplete="off" /><br />
<label for="phone">Please enter your phone number:</label>
<input type="number" name="phone" id="phone" value="" class="required" autocomplete="off" />
<br><br>
<label for="other">Other comments</label>
<textarea name="other" id="other" autocomplete="off" placeholder="Anything else you'd like to add?">
</textarea>
<p><strong id="error"></strong></p>
<br><br>
<input type="submit" id="save" name="save" value="Submit Form" />
<p id="response"></p>
</form>
I think this may help you to resolve your problem.
Missing double quotes for name value in your SQL.
VALUES ("'.$name.'", "'.$email.'", "'.$phone.'","'.$other.'")';
Use Firefox/firebug to see the parameters and result, and add an echo($query); so you can see it in firebug.
'E-mail list' doesn't seem like convenient database name, though it should be okay.
Anyway, your goal should be to display all possible error that may occur.
So, you have to always check for the errors and report them in more usable form than just 'Cannot save data.'
Always check your connect
$mysqli = new mysqli('localhost', 'root', '', 'E-mail list');
if ($mysqli->connect_error) {
trigger_error($mysqli->connect_error);
}
same for the query
if (!$mysqli->query($query)) {
trigger_error($mysqli->error." ".$query);
}
If you see no error messages - check the logic of your code: if you ever run the code, if you run the code you wrote, if PHP works, typos etc.
I'm building a contact us page that also uses a reCaptcha, but im having a few issues with it. I fill in all of the fields in the contact form and the correct reCaptcha words, but the form does not submit. I'm assuming this is something to do with the validation, but wondered if someone might be able to spot where i'm going wrong?
The PHP code at the top of my page looks like this;
<?php include('includes/session.php');
$err = '';
$success = '';
if(isset($_POST["docontact"]) && $_POST["docontact"] == "yes") {
//get form details
$form = new stdClass();
$form->name = sanitizeOne($_POST["name"], "str");
$form->email = sanitizeOne($_POST["email"], "str");
$form->phone = sanitizeOne($_POST["phone"], "str");
$form->mysevenprog = sanitizeOne($_POST["mysevenprog"], "str");
$form->enquiry = sanitizeOne($_POST["enquiry"], "str");
$form->howfindsite = sanitizeOne($_POST["howfindsite"], "str");
//Check for errors (required: name, email, enquiry)
if($form->name == "") {
$err .= '<p class="warning">Please enter your name!</p>';
}
if($form->email == "") {
$err .= '<p class="warning">Please enter your email address!</p>';
}
if($form->enquiry == "") {
$err .= '<p class="warning">Please supply an enquiry message!</p>';
}
//Send Email
if($err == "") {
$mailer = new BlueMailer();
$mailer->AddAddress(Configuration::getVar("developer_email"), Configuration::getVar("admin_email_name"));
include('templates/email/contact-us-admin.php');
if(!$mailer->Send()) {
$err .= "<p>There was an error sending submitting your request!, Please try again later.";
} else {
$success = 'thanks';
}
}
} else {
//Initialise empty variables
$form = new stdClass();
$form->name = "";
$form->email = "";
$form->phone = "";
$form->mysevenprog = "";
$form->enquiry = "";
$form->howfindsite = "";
}
?>
And then in the body of my page I have the form as follows;
<?php if($err != "") : ?>
<div class="error">
<?php echo $err; ?>
</div>
<?php endif; ?>
<?php if($success == 'thanks') : ?>
<h3>Thank you for your enquiry</h3>
<p>Your enquiry has been successfully sent. Someone will contact you shortly.</p>
<?php else: ?>
<h3>If you are looking to advertise with us, have some feedback about some of our programming or want to say 'Hi' please use the fields below</h3>
<form name="contactus" id="contactus" method="post" action="<?php echo $_SERVER['SCRIPT_NAME'] ?>">
<ul>
<li><label for="name">Your name: *</label> <input name="name" id="name" class="textbox" style="width: 75%;" type="text" value="<?php echo $form->name ?>" /></li>
<li><label for="email">Email address: *</label> <input name="email" id="email" class="textbox" style="width: 75%;" type="text" value="<?php echo $form->email ?>" /></li>
<li><label for="phone">Telephone:</label> <input name="phone" id="phone" class="textbox" style="width: 75%;" type="text" value="<?php echo $form->phone ?>" /></li>
<li><label for="mysevenprog">My Seven programme</label> <input name="mysevenprog" class="textbox" style="width: 75%;" type="text" value="<?php echo $form->mysevenprog ?>" /></li>
<li><label for="enquiry">Enquiry/Message: *</label> <textarea name="enquiry" class="textarea" rows="5" cols="30" style="width: 75%;" id="enquiry"><?php echo $form->enquiry ?></textarea></li>
<li><label for="howfindsite">How did you find out about our site?</label> <input name="howfindsite" id="howfindsite" class="textbox" style="width: 75%;" type="text" value="<?php echo $form->howfindsite ?>" /></li>
<li>
<?php
require_once('recaptchalib.php');
// Get a key from http://recaptcha.net/api/getkey
$publickey = "";
$privatekey = "";
# the response from reCAPTCHA
$resp = null;
# the error code from reCAPTCHA, if any
$error = null;
# was there a reCAPTCHA response?
if ($_POST["recaptcha_response_field"]) {
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if ($resp->is_valid) {
echo "You got it!";
} else {
# set the error code so that we can display it
$error = $resp->error;
}
}
echo recaptcha_get_html($publickey, $error);
?>
</li>
<li><input type="submit" value="Submit Form" class="button" /></li>
</ul>
<input type="hidden" name="docontact" value="yes" />
</form>
<?php endif; ?>
The form gets rendered like this in the browser;
<form name="contactus" id="contactus" method="post" action="/contact-us2.php">
<ul>
<li><label for="name">Your name: *</label> <input name="name" id="name" class="textbox" style="width: 75%;" type="text" value="" /></li>
<li><label for="email">Email address: *</label> <input name="email" id="email" class="textbox" style="width: 75%;" type="text" value="" /></li>
<li><label for="phone">Telephone:</label> <input name="phone" id="phone" class="textbox" style="width: 75%;" type="text" value="" /></li>
<li><label for="mysevenprog">My Seven programme</label> <input name="mysevenprog" class="textbox" style="width: 75%;" type="text" value="" /></li>
<li><label for="enquiry">Enquiry/Message: *</label> <textarea name="enquiry" class="textarea" rows="5" cols="30" style="width: 75%;" id="enquiry"></textarea></li>
<li><label for="howfindsite">How did you find out about our site?</label> <input name="howfindsite" id="howfindsite" class="textbox" style="width: 75%;" type="text" value="" /></li>
<li>
<script type="text/javascript" src="http://api.recaptcha.net/challenge?k=XXXXXXXXXXXXXXXXXXX"></script>
<noscript>
<iframe src="http://api.recaptcha.net/noscript?k=XXXXXXXXXXXXXXXXXXXX" height="300" width="500" frameborder="0"></iframe><br/>
<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
</noscript>
</li>
<li><input type="submit" value="Submit Form" class="button" /></li>
</ul>
<input type="hidden" name="docontact" value="yes" />
</form>
Just use Zend_Service_ReCaptcha. You'll integrate this service just with few lines:
//Creating instance
$recaptcha = new Zend_Service_ReCaptcha($pubKey, $privKey);
//Display output
echo $recaptcha->getHTML();
//Handling input
$result = $recaptcha->verify(
$_POST['recaptcha_challenge_field'],
$_POST['recaptcha_response_field']
);
//And finally validate captcha
if ($result->isValid()) {
//Cool!
}
Take a look at Using reCAPTCHA to stop spam in PHP.