PHP contact form not working and giving errors - php

I am trying to set up a contact form at:
http://48hrcodes.com/contact.php
however I am trouble getting it to work.
Here is the code I am using:
<?php
/**
* Change the email address to your own.
*
* $empty_fields_message and $thankyou_message can be changed
* if you wish.
*/
// Change to your own email address
$your_email = "";
// This is what is displayed in the email subject line
// Change it if you want
$subject = "48hrcodes contact form";
// This is displayed if all the fields are not filled in
$empty_fields_message = "<p>Please go back and complete all the fields in the form.</p>";
// This is displayed when the email has been sent
$thankyou_message = "<p>Thank you. Your message has been received.</p>";
// You do not need to edit below this line
$name = stripslashes($_POST['txtName']);
$email = stripslashes($_POST['txtEmail']);
$message = stripslashes($_POST['txtMessage']);
if (!isset($_POST['txtName'])) {
?>
<html lang="en">
<head>
<link href='https://fonts.googleapis.com/css?family=Droid+Sans:400,700' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="css/style.css">
<title>Free 48hr Xbox Live Gold Codes</title>
</head>
<body>
<div id="content">
<div id="c1"> <center>
<header id="nav">
<ul>
<li>Home</li>
<li>Get Your Code</li>
<li>Testimonials and Proof</li>
<li>Frequently Asked Questions</li>
<li>Contact Us</li>
</ul>
</header>
<img class="clear" src="img/grab3.png" alt="header">
</center>
<form class="form" method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<p class="name">
<input type="text" name="txtName" id="name" placeholder="John Doe" />
<label for="name">Name</label>
</p>
<p class="email">
<input type="text" name="txtEmail" id="email" placeholder="mail#example.com" />
<label for="email">Email</label>
</p>
<p class="text">
<textarea name="txtMessage" placeholder="Write something to us" /></textarea>
</p>
<p class="submit">
<input type="submit" value="Send" />
</p>
</form>
<div id="cttxt">
<h3>
Contact Us
</h3>
<p>
Simply send us message using the contact form to the left and we will get back to you within 24-48 hours.
</p>
</div>
<center>
<footer>
© 48hrcodes.com 2013 - site by ollie rex
</footer>
</div></center>
</div>
</body>
</html>
<?php
}
elseif (empty($name) || empty($email) || empty($message)) {
echo $empty_fields_message;
}
else {
// Stop the form being used from an external URL
// Get the referring URL
$referer = $_SERVER['HTTP_REFERER'];
// Get the URL of this page
$this_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"];
// If the referring URL and the URL of this page don't match then
// display a message and don't send the email.
if ($referer != $this_url) {
echo "You do not have permission to use this script from another URL, nice hacking attempt moron.";
exit;
}
// The URLs matched so send the email
mail($your_email, $subject, $message, "From: $name <$email>");
// Display the thankyou message
echo $thankyou_message;
}
?>
I get errors at the top of the page, as well as when i submit the form, the email i get only has the messagebox text, not the name or email.
I have tried everything i could think of, however it still fails to send anything except the msg variable.
Thanks :)

change
$name = stripslashes($_POST['txtName']);
$email = stripslashes($_POST['txtEmail']);
$message = stripslashes($_POST['txtMessage']);
To,
$name = (isset($_POST['txtName']))?stripslashes($_POST['txtName']):"";
$email = (isset($_POST['txtEmail']))?stripslashes($_POST['txtEmail']):"";
$message = (isset($_POST['txtMessage']))?stripslashes($_POST['txtMessage']):"";
To avoid the warnings at the top.

Use
like this
if(isset($_POST['txtName'])
{
$name = stripslashes($_POST['txtName']);
}

Related

New to PHP. Can't figure out what is missing to send mail

I'm new to PHP and having a hard time getting the PHP to mail when the contact form is filled out and submit is pressed. I've posted the PHP and HTML files. Any help is very much appreciated.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Jaza Solutions - Contact</title>
<link rel = "stylesheet"
type = "text/css"
href = "jazasolutions.css" />
</head>
<body>
<div id = "header">
<img src="jazasolutions.png" alt = "Jaza Solutions, LLC">
</div>
<div id="nav">
<ul>
<li><a href=JazaSolutionsContact.html>Contact</a></li>
<li><a href=JazaSolutionsAboutUs.html>About Us</a></li>
<li><a href=JazaSolutionsCourses.html>Courses</a></li>
<li><a href=JazaSolutions.html>Home</a></li>
</ul>
</div>
<div class="sideRight">
<p> Jaza Solutions</p>
<p> 9818 Ushers Place </p>
<p> Waldorf, MD 20601 </p>
<br>
<p>301-861-2133</p>
<p>info#jazasolutions.com</p>
</div>
<div class = "main">
<p> Get the Management Certification you need to make the next step in your career! </p>
<br>
<p>SEND A MESSAGE</p>
<form class="contact-form" action="contactform.php" method="post">;
<input type="text" name="name" placeholder="Full Name">
<input type="text" name="mail" placeholder="Email">
<input type="text" name="subject" placeholder="Subject">
<textarea name="message" placeholder="Message"></textarea>
<button type="submit" name="submit">SEND MAIL</button>
</form>
</div>
</body>
</html>
The PHP code is posted here. This should send an email, but I can't figure out why it's not working.
<?php
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$subject = $_POST['subject'];
$mailFrom = $_POST['mail'];
$message = $_POST['message'];
$mailTo = "pmckeown#jazasolutions.com";
$headers = "From: ".$mailFrom;
$txt = "You have received an email from ".$name.".\n\n".$message;
mail($mailTo, $subject, $txt, $headers);
header("Location: index.php?mailsend");
}
?>
I tried something similar a few years ago. After hours of searching I got a Tipp I'll never forget. The Mail RFC is so huge and has so many special cases that you don't do yourself a favor when you try to implement this on your own (Even if you get your Mail send it's most likely that it will be marked as spam from most of the Mail-Services out there because you missed some special handling or some tags). This becomes really funny when you try to send an attachment or even images in your mailer implementation. I'd recommend you try one of the proven Mail-Libraries for PHP like PHPMailer. You can expect that most of the common use-cases work out of the box without great problems.

PHP Checkbox Values Not Saved During Error Check or Posting

The "newvar_" values for "029, 032 and 033" are not being remembered during error-checking, nor are they being posted when a corrected form is submitted.
The "name" field works correctly both on error checking and posting.
The form default for the all checkboxes is not selected.
The user should be able to select only the forms they wish. Their selection should post to the txt file along with their name.
The validation library am using can be found at: http://www.benjaminkeen.com/software/php_validation
Thanks in advance for your assistance.
<?php
// Eliminate server error notices except for parse errors
error_reporting(E_PARSE);
// Receiving variables
$errors = array(); // set the errors array to empty, by default
$fields = array(); // stores the field values
if (isset($_POST['submit']))
{
// Import the validation library
require("../include/validation.php");
$rules = array(); // stores the validation rules
// Rules specific to this form
$rules[] = "required,name,Please enter Your Name.";
$rules[] = "length<71,name,Your Name is too long.";
// Check the user's entries for errors based upon above rules
$errors = validate_fields($_POST, $rules);
// If there were errors, re-populate the form fields with user entries
if (!empty($errors))
{
$fields = $_POST;
}
// If there were no errors
else
{
// Redirect to a "thank you" page URL shown below
header("Location: thank-you.php");
}
}
// Count the errors. If none process the form data
if (count($errors) == 0) {
// Location of flat file database - absolute path
$datafile_01 = '/home/domain/public_html/Forms.txt';
// Strip-out the HTML tags
$_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
// Write successfully submitted form data to flat file database
if ($_POST['submit']) {
$file = fopen($datafile_01, "a");
if (!$file) {
die("Can't write to database file");
}
// Set timezone to match delivery location
date_default_timezone_set('America/New_York');
$date = date('Y m-d g:i:s a');
// Select and code the fields being posted
$name = $_POST['name'];$name=($name);
//FORMS & SUPPLIES
// Standard Forms they requested
// Change the checkbox 'on' to something else (defined by $Newvar)
if($Form_F_029 == 'on') { $Newvar_029 = &$Form_F_029; $Newvar_029 = "X"; }
if($Form_F_032 == 'on') { $Newvar_032 = &$Form_F_032; $Newvar_032 = "X"; }
if($Form_F_033 == 'on') { $Newvar_033 = &$Form_F_033; $Newvar_033 = "X"; }
// Format the fields for the flat file
fwrite($file,
"Name:\t $name\n
REQUESTED FORMS AND SUPPLIES:\n
STANDARD FORMS ++++++++++++++++++++
Form F-029:\t $Newvar_029
Form F-032:\t $Newvar_032
Form F-033:\t $Newvar_033\n
=============================================================================== EOF =\n\n);"
fclose($file);
}
// Format and send email notice of successful submittal
if ($_POST['submit']) {
$sn_header = "From: Inquiries Database\n"
. "Reply-To: no_reply#domain.com\n";
$sn_subject = "Ordering Supplies Request";
$sn_email_to = "someone#domain.com";
$sn_message = "Please check the database for a recent submission.\n\n"
. "This is a post-only message.\n\n"
. "Do not reply.\n";
#mail($sn_email_to, $sn_subject ,$sn_message ,$sn_header ) ;
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Form Test</title>
<meta charset="utf-8" />
<meta name="viewport"
content="width=device-width, initial-scale=1" />
<?php //This CSS needed only for forms to style Modal ?>
<link rel="stylesheet"
href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"
media="screen" />
</head>
<body>
<!-- Wrapper -->
<div id="wrapper" class="divided">
<section class="wrapper style1 align-left">
<div class="inner">
<h2 class="color-1">Measuring & Ordering Supplies</h2>
<form action="<?=$_SERVER['PHP_SELF']?>" name="inquiry" method="post">
<div class="field">
<label style="margin:1rem 0 .25rem 0"><i class=" color-1 fa fa-star"></i> Your Name:</label>
<input type="text" name="name" id="name" value="<?=$fields['name']?>" />
</div>
<div class="field" style="padding-top:1rem">
<label style="font-size:110%; margin-bottom:0"><b class="color-1">Standard Forms</b>
<span style="font-weight:300; font-size:80%">Check box to order | Click name to download PDF</span><br />
</label>
</div>
<div class="field third first" style="padding-top:10px">
<input type="checkbox" id="Form_F_029" name="Form_F_029" <?php if($Form_F_029 == "on"){echo "CHECKED";}?> />
<label for="F_029">Form F 029
</label>
</div>
<div class="field third" style="padding-top:10px">
<input type="checkbox" id="Form_F_032" name="Form_F_032" <?php if($Form_F_032 == "on"){echo "CHECKED";}?> />
<label for="Form_F_032">Form F 032
</label>
</div>
<div class="field third" style="padding-top:10px">
<input type="checkbox" id="Form_F_033" name="Form_F_033" <?php if($Form_F_033 == "on"){echo "CHECKED";}?> />
<label for="Form_F_033">Form F 033
</label>
</div>
<ul class="actions" style="padding-top:30px">
<li><input type="submit" class="button small" name="submit" id="submit" value="Submit Request" /></li>
</ul>
</form>
</div>
<div id="error" title="Form Errors:">
<?php
// if $errors is not empty display them in the modal
if (!empty($errors))
{
echo "<div style=\"padding:15px 15px 0 15px\">";
echo "<ul style=\"margin-bottom:20px\">";
foreach ($errors as $error)
echo "<li style=\"font-size:15px; padding:5px\">$error</li>";
echo "</ul></div>";
}
?>
</div>
</section>
<!-- Footer -->
</div>
<!-- Scripts -->
<?php include $_SERVER["DOCUMENT_ROOT"] . "/assets/includes/php/javascripts-01.php"; ?>
<?php // Supporting scripts for Error Modal ?>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
<?php if( isset( $_POST["submit"] ) ){ ?>
$('#error').dialog({
height: 380,
width: 260,
modal: true,
resizable: false,
dialogClass: 'no-close error-dialog'
});
<?php } ?>
</script>
</body>
</html>
The values of $Form_F_029, _032, _033 are never set.
You copied the POST variables into $fields:
$fields = $_POST;
So this worked as intended:
<input type="text" name="name" id="name" value="<?=$fields['name']?>" />
But uses of $Form_F_0xx are treated as null, undefined or false depending on context:
<input type="checkbox" id="Form_F_029" name="Form_F_029" <?php if($Form_F_029 == "on"){echo "CHECKED";}?> />
You could fix this by setting
$Form_F_029 = $fields['Form_F_029'];
or
$Form_F_029 = $_POST['Form_F_029'];
etc.
For debugging problems like this it can help to include the values of variables and arrays in your output, for example in a comment or pre tag:
echo "<!-- 29= $Form_F_029, 32 = $Form_F_032 -->"; // DEBUGGING
echo "<pre>- 29= $Form_F_029, 32 = $Form_F_032 </pre>"; // DEBUGGING
Just remember to delete them or comment them out later.

PHP code error with contact form

I am beginner in web developing, I am building a website which has contact form and when the details are entered the details has to be sent to my mail id. But I am not sure why the code is not working.
<?php
if(isset($_POST["submit"])){
// Checking For Blank Fields..
if($_POST["name"]==""||$_POST["email"]==""||$_POST["note"]==""){
echo "Fill All Fields..";
}else{
// Check if the "Sender's Email" input field is filled out
$email=$_POST['email'];
// Sanitize E-mail Address
$email =filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate E-mail Address
$email= filter_var($email, FILTER_VALIDATE_EMAIL);
if (!$email){
echo "Invalid Sender's Email";
}
else{
$message = $_POST['note'];
$headers = 'From:'. $email2 . "\r\n"; // Sender's Email
$headers .= 'Cc:'. $email2 . "\r\n"; // Carbon copy to Sender
// Message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// Send Mail By PHP Mail Function
mail("[ email removed ]", $message, $headers);
echo "Your mail has been sent successfuly ! Thank you for your feedback";
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hire-a-Tent</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="css/style.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<![endif]-->
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<!-- Javascript -->
<script src="js/jquery.placeholder.js"></script>
<script src="js/custom.js"></script>
<!-- Fav and touch icons -->
<link rel="shortcut icon" href="favicon.ico">
</head>
<body>
<div class="background">
<div class="wrapper">
<header>
<div class="tel"><span>CALL US:</span> 9738479234 <br /><span style="padding-left:150px;">9731015469</span></div>
<div class="social">
<img src="images/facebook.png" alt="" />
<img src="images/twitter.png" alt="" />
</div>
</header>
<div class="sidebar">
<div class="order-form">
<div class="order-form-head">
<h1>Rent -a- Tent</h1>
</div>
<div class="taxi-line"></div>
<!-- Contact Form -->
<form action="email_code.php" id="form" method="post" name="form">
<div class="inp"><input type="text" class="required" name="name" id="name" placeholder="Name..." /></div>
<div class="inp"><input type="text" class="required" name="tel" id="tel" placeholder="Telephone..." /></div>
<div class="inp"><input type="text" class="required" name="email" id="email" placeholder="Email..." /></div>
<div class="inp"><textarea class="required" name="note" id="note" placeholder="Message..."></textarea></div>
<button type="submit"></button>
<div class="spacer"></div>
</form>
<?php include "email_code.php"?>
</div>
<div class="address-box">
<img src="images/icon.png" class="icon" alt="" />
<div class="text">
<span>We are located at</span><br />
85, 4th cross road,<br />
GKW layout, vijayanagar<br />
Bengaluru-40
</div>
</div>
</div>
<div class="character">
<!-- <img src="images/transparent2.png" class="taxi-driver" alt="" /> -->
<marquee behavior="alternate">T2 Tent: Rs 100/day --- T3 Tent: Rs 200/day -- Sleeping Bag: Rs 50/day --</marquee>
</div>
<div class="spacer"></div>
<footer>
<p><strong><br/><br/>Hire-a-tent</strong> © All Rights Reserved. <!--Developed by the Frequency Themes --></p>
</footer>
</div>
</div>
</body>
</html>
There are a few things wrong here, so please go over my entire answer carefully.
Firstly, your entire code's execution is relying on the conditional statement it's set in:
if(isset($_POST["submit"])){...}
where it is looking for and is relying on a named attribute of the same name, which would most likely be your submit button being:
<button type="submit"></button>
It needs to be named:
<button type="submit" name="submit"></button>
or use an input type with a name attribute:
<input type="submit" name="submit" value="Submit">
Then you have an undefined variable $email2 which would most likely need to be $email, as per:
$email=$_POST['email'];
Having used error reporting, would have both signaled an "Undefined index submit..." warning, as well as "Undefined variable email2...".
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Now, this line:
mail("[ email removed ]", $message, $headers);
It is missing the "subject" parameter, which is an important parameter when using mail().
I.e.:
mail("[ email removed ]", $subject, $message, $headers);
therefore, you will need to add a variable for it.
I.e.:
$subject = "Form submission";
For more information on mail() and headers, visit:
http://php.net/manual/en/function.mail.php
From the manual:
bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )
To check if mail() has been in fact executed, change:
mail("[ email removed ]", $message, $headers);
to
if(mail("[ email removed ]", $message, $headers)){
echo "Mail has been sent.";
}
else{
echo "Error. Check your mail logs.";
}
If/when you see "Mail has been sent.", then mail() has done its job.
If you don't receive mail, then check your Spam or contact your hosting company if you're on a hosted site.
If you're running this from your own computer, then make sure that PHP and mail are in fact installed, running and configured properly.
Footnotes:
You're using the following twice, which one of them can be safely removed:
$email= filter_var($email, FILTER_VALIDATE_EMAIL);
EDIT:
To add other form variables to the message, first declare the POST variables:
$name=$_POST['name'];
$email=$_POST['email'];
$tel=$_POST['tel'];
Then change $message = $_POST['note']; to $comment = $_POST['note'];
and then do:
$message = "$name\n$email\n$tel\n$comment";
The \n adds line breaks.

PHP form not processing in process.php

I'm having difficulty figuring out why my PHP form is processing on process.php but not returning to the form page with the appropriate $messages. Am I missing a line of code? I wrote this all up myself and it's the first time.
Here is my html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test Contact Form - jQuery</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
<h3>Contact Us</h3>
<?php echo $contact_message; ?>
<form id="myForm" method="post" action="process.php">
<input name="name" type="text" value="<?php echo $_POST[name]; ?>" placeholder="Name" required/>
<br>
<input name="email" type="email" value="<?php echo $_POST[email]; ?>" placeholder="you#yourmail.com" required/>
<br>
<textarea name="message" class="message" placeholder="We can answer your questions." required>
<?php echo $_POST[message]; ?>
</textarea>
<br>
<button type="submit" name="submit" class="btn send">
<img src="img/send.png">
</button>
<br>
<?php echo $contact_success_message; ?>
</form>
<!--close contact form-->
</body>
</html>
And here is my process.php
<?php
//checks for valid email
function is_valid_email($email) {
$result = true;
$pattern = '/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\#([a-z0-9])(([a-z0-9-])*([a-z0-9]))+(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i';
if(!preg_match($pattern, $email)) {
$result = false;
}
return $result;
}
//when send is pressed, validate fields
if(isset($_POST['submit'])) {
$valid = true;
$contact_message = '';
if ( $_POST['name'] == "" ) {
$contact_message .= "You forgot to tell us your name. ";
$valid = false;
}
if ( !is_valid_email($_POST['email']) ) {
$contact_message .= "A valid email is required, don't worry we don't share it with anyone. ";
$valid = false;
}
if ( $_POST['message'] == "" ) {
$contact_message .= "What did you want to ask us? ";
$valid = false;
}
//if everything checks out, send the message!
if ( $valid == true ) {
$safe_email = str_replace("\r\n","",$_POST[email]);
$mail = "From: $_POST[name]\n";
$mail .= "Email: $_POST[email]\n";
$mail .= "$_POST[message]\n";
mail('ME#MYEMAIL.COM','New Contact from RN+',$mail,"From: $safe_email\r\n");
$contact_success_message = 'Brilliant I say! We will be in contact with you shortly.';
//clear form when submission is successful
unset($_POST);
}
}
?>
I could have sworn that I've used this before but this time it's not returning to the contact page.
It looks like you meant to use the code like this:
form.php
<?php include 'process.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test Contact Form - jQuery</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
<h3>Contact Us</h3>
<?php echo $contact_message; ?>
<form id="myForm" method="post" action="process.php">
<input name="name" type="text" value="<?php echo $_POST[name]; ?>" placeholder="Name" required/><br>
<input name="email" type="email" value="<?php echo $_POST[email]; ?>" placeholder="you#yourmail.com" required/><br>
<textarea name="message" class="message" placeholder="We can answer your questions." required><?php echo $_POST[message]; ?></textarea><br>
<button type="submit" name="submit" class="btn send"><img src="img/se
__
formnd.png"></button><br>
<?php echo $contact_success_message; ?>
</form><!--close contact form-->
</body>
</html>
The form processor will set the appropriate variables you are outputting in your HTML code. Since process.php checks if the method is POST, you don't have to do that in the form page.
If you want process.php to redirect back to your form, you need to add a PHP header code like: header('Location: http://www.example.com/form.php');
If you want to carry through any data back to the original page, include it in the URL as a GET variable: header('Location: http://www.example.com/form.php?message='.$messagetext); You can then retrieve this on your form page through use of GET: echo $contact_success_message = $_GET['message'];
Do not forget to exit(); or die(); after your redirect!
If you don't have any reason for excluding a single PHP page, you could merge the two (form and process) into one php page.
<?php
//checks for valid email function
...
if(isset($_POST['submit'])) {
...
}
?>
...your HTML goes here...
This will display just the form if no data has been submitted, and if the form has been submitted will "reload" the page, perform the action, and display the appropriate message. Change the form action to action="" so the file will post to itself.
I would recommend using jQuery validation. It is easier and will help with any issues you might have in returning the message.
http://docs.jquery.com/Plugins/Validation
Something like this...
$("#myForm").validate({
rules: {
name: { required: true; }
},
messages: {
name: "You forgot to tell us your name.",
}
});
You can do this for email fields and for your whole form. You can find plenty of examples online.
Just include your other fields. If you do it this way the validation is client side and the form will process and then you forward to a thank you for contacting us page.

Form Validation Error Message not showing

Was hoping for some fresh eyes on this. I've got a page which will add a new event to a database. All 3 fields are required, so if they are empty when the submit button is pushed the error message should appear. Anyone know why it isn't showing the error message? Thanks in advance!
Here's the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>ADMIN - Repetative Strain Injury UK</title>
<meta http-equiv="content-type" content="application/xhtml; charset=utf-8" />
<link href="/iis_project/view/css/mycss.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<!-- wrapper div for positioning -->
<div class="grid10 first" id="header">
<!-- Header Section -->
<img src="/iis_project/view/img/banner.jpg" alt="RSI UK Banner" width="1090" height="75"/>
</div>
<div class="grid11 first" id="date">
<!-- Date Section -->
<?php
include ("date.php");
?>
</div>
<div class="grid2 first" id="col1">
<!-- Left column Section -->
<h1>Navigation</h1>
<p>
<strong>Home</strong>
</p>
<p>
<strong>About Us</strong>
</p>
<p>
<strong>Register</strong>
</p>
<p>
<strong>Log In</strong>
</p>
<p>
<strong>Events</strong>
</p>
<p>
<strong>Acknowledgements</strong>
</p>
</div>
<div class="grid6" id="col2">
<!-- Middle column Section -->
<h1>New Event</h1>
<p>
As an admin you have the right to create a new event. Simply fill out the form below and hit submit.
</p>
<?php
// creates the new record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($name, $date, $location, $error22)
{
?>
<?php
// if there are any error22s, display them
if ($error22 != '') {
echo '<div style="padding:4px; border:1px solid red; color:red;">' . $error22 . '</div>';
}
?>
<form action="" method="post">
<div>
Name:
<input type="text" name="name" value="<?php echo $name;?>" />
<br/>
Date:
<input type="text" name="date" value="<?php echo $date;?>" />
<br/>
Location:
<input type="text" name="location" value="<?php echo $location;?>" />
<br/>
<input type="submit" name="submit_event" value="Submit">
</div>
</form>
<?php
}
// connect to the database
include ("home_connection.php");
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$date = mysql_real_escape_string(htmlspecialchars($_POST['date']));
$location = mysql_real_escape_string(htmlspecialchars($_POST['location']));
// check to make sure all fields are entered
if ($name == '' || $date == '' || $location == '')
{
// generate error22 message
$error22 = 'error22: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($name, $date, $location, $error22);
}
else
{
// save the data to the database
mysql_query("INSERT events SET name='$name', date='$date', location='$location'")
or die(mysql_error22());
// once saved, redirect back to the view page
header("Location: login_success_admin.php");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','','');
}
?>
</div>
<div class="grid2" id="col3">
<!-- Right column Section -->
<h1>Newsletter</h1>
<h2>Sign up to our newsletter:</h2>
<?php
include ("newsletter.php");
?>
</div>
<div class="grid10 first" id="footer">
<!-- Footer Section -->
<p>
Repetative Strain Injury UK © West Street, Jubille Way, Leeds, LS6 3QW. Email: info#rsiuk.org
Tel: 0113 658102. Reg charity no: 1032941
</p>
</div>
</div> <!-- end container -->
</body>
</html>
You have the submit name as "submit_event"
So you must use
if (isset($_POST['submit_event'])) {
.
.
.
}
Hope it helps
Try adding
<input type="hidden" name="submit" value="1" />
to your form. The $_POST array does not have a 'submit' value in the code you have provided, so it's just going to display the form again.

Categories