I'm trying to create a contact form so people can leave messages on a website. Essentially I want it to be a single page process with a success or error message appearing on the same page. However, I'm a beginner in PHP so I'm not sure where to go from where I'm currently stuck at.
So far I've gotten the form to submit but always returns with missing fields even though no fields are missing. Also the page reloads and returns to the top of the page. Is there a way, after form submission, to have it not return to the top of the page after form submission?
Here's the HTML form, essentially it's a single page website segmented into different slides. Upon form submission I want the page to stay on slide4 where the form and success/error message will be.
<div id="slide4">
<div class="slidetitle">Contact Me</div>
<div class="content">
<form action="index.php" method="POST" id="contactform" target="_self">
<input type="hidden" name="postid" value="<?php $postid?>">
<table>
<tr><td><b>First Name:</b></td><td><input type="text" name="firstName" size="45" value="<?php $firstName?>"></td></tr>
<tr><td><b>Last Name:</b></td><td><input type="text" name="lastName" size="45" value="<?php $lastName?>"></td></tr>
<tr><td><b>Email:</b></td><td><input type="email" name="email" size="45" value="<?$email?>"></td></tr>
<tr><td><b>Phone:</b></td><td><input type="tel" name="phone" size="45" value="<?$phone?>"></td></tr>
<tr><td><b>Content:</b></td><td><textarea name="content" form="contactform" rows="10" cols="100"><?php echo $content; if (empty($content)){ echo "Enter text here...";} ?></textarea></td></tr>
<tr><td colspan=2 style="text-align: center"><input type=submit name="submit1" value="Leave me a message"></td></tr>
</table>
</form>
<div id="contactoutput">
<?php $output ?>
</div>
</div>
</div>
And here's the Updated PHP for the form after implementing the changes Frank suggested.
<?php
$firstName = "";
$lastName= "";
$email = "";
$phone = "";
$content = "";
$errMsg = "";
?>
<?php $errMsg ?>
<?php
if (isset($_POST['submit1'])) {
// ==========================
//validate user input
// set up the required array
$required = array("firstName","lastName","email","phone","content"); // note that, in this array, the spelling of each item should match the form field names
// set up the expected array
$expected = array("firstName","lastName", "email","phone","content","postid"); // again, the spelling of each item should match the form field names
$missing = array();
foreach ($expected as $field){
// isset($_POST[$field]): Note that if there is no user selection for radio buttons, checkboxes, selection list, then $_POST[$field] will not be set
// Under what conditions the script needs to record a field as missing -- $field is required and one of the following two (1) $_POST[$field] is not set or (2) $_POST[$field] is empty
//echo "$field: in_array(): ".in_array($field, $required)." empty(_POST[$field]): ".empty($_POST[$field])."<br>";
if (in_array($field, $required) && (!isset($_POST[$field]) || empty($_POST[$field]))) {
array_push ($missing, $field);
} else {
// Passed the required field test, set up a variable to carry the user input.
// Note the variable set up here uses a variable name as the $field value. In this example, the first $field in the foreach loop is "title" and a $title variable will be set up with the value of "" or $_POST["title"]
if (!isset($_POST[$field])) {
//$_POST[$field] is not set, set the value as ""
${$field} = "";
} else {
${$field} = $_POST[$field];
}
}
}
//print_r ($missing); // for debugging purpose
/* add more data validation here */
// ex. $price should be a number
/* proceed only if there is no required fields missing and all other data validation rules are satisfied */
$stmt = $conn->stmt_init();
$sql = "Insert Into msg_table16 (firstName, lastName, email, content, phone, postid) values (?, ?, ?, ?, ?, ?)";
if($stmt->prepare($sql)){
// Note: user input could be an array, the code to deal with array values should be added before the bind_param statement.
$stmt->bind_param('ssssii',$firstName, $lastName,$email,$content,$phone,$postid);
$stmt_prepared = 1; // set up a variable to signal that the query statement is successfully prepared.
}
if ($stmt_prepared == 1){
if ($stmt->execute()){
$output = "<p>The following information has been saved in the database:<br><br>";
foreach($_POST as $key=>$value){
$output .= "<b>$key</b>: $value <br>"; //$key (form field names) may not be very indicative (ex. lname for the last name field), you can set up the form field names in a way that can be easily processed to produce more understandable message. (ex. use field names like "Last_Name", then before printing the field name, replace the underscore with a space. See php solution 4.4)
}
} else {
//$stmt->execute() failed.
$output = "<p>Database operation failed. Please contact the webmaster.";
}
} else {
// statement is not successfully prepared (issues with the query).
$output = "<p>Database query failed. Please contact the webmaster.";
}
} else {
// $missing is not empty
$output = "<p>The following required fields are missing in your form submission. Please check your form again and fill them out. <br>Thank you.<br>\n<ul>";
foreach($missing as $m){
$output .= "<li>$m";
}
$output .= "</ul>";
}
?>
So in summary, why is the form returning that fields are missing when I would fill them all in so there shouldn't be any missing. AND How do I have the form submit and not reload and return to the top of the page?
I apologize if there is any required information that I did not post in advance, if you guys need anymore code snippets please let me know. Thank you guys!
Just tried to make something of your code. But there are a few things you really need to take a look at:
You are missing some closing tags in your html, for example you are missing a </div> & </form> tag.
You can put all your php code at the top of your page. It's a best practice to seperate your logic from your view.
Proper php opening and closing tags looks like the following : <?php ... ?> not <= or <?
A proper PDO connection looks like this
<?php
try {
$db = new PDO("pgsql:dbname=pdo;host=localhost", "username", "password" );
echo "PDO connection object created";
}
catch(PDOException $e){
echo $e->getMessage();
}
?>
If you want to concatenate a ul to output your errors you will have to do that the as follow:
<?php
$str = '<ul>';
$str .= '<li></li>';
$str .= '<li></li>';
$str .= '</ul>';
?>
The foundation of the errors you are getting are caused by points like the above. Goodluck and ask if you have any more questions.
What about closing the form tag:
<div id="slide4">
<div class="slidetitle">Contact Me</div>
<div class="content">
<form action="index.php#slide4" method="POST" id="contactform">
<input type="hidden" name="postid" value="<?=$postid?>">
<table>
<tr>
<td><b>First Name:</b>
</td>
<td>
<input type="text" name="firstName" size="45" value="<?=$firstName?>">
</td>
</tr>
<tr>
<td><b>Last Name:</b>
</td>
<td>
<input type="text" name="lastName" size="45" value="<?$lastName?>">
</td>
</tr>
<tr>
<td><b>Email:</b>
</td>
<td>
<input type="email" name="email" size="45" value="<?$email?>">
</td>
</tr>
<tr>
<td><b>Phone:</b>
</td>
<td>
<input type="number" name="phone" size="45" value="<?$phone?>">
</td>
</tr>
<tr>
<td><b>Content:</b>
</td>
<td>
<textarea name="content" form="contactform" rows="10" cols="100">
<?php echo $content; if (empty($content)){ echo "Enter text here...";} ?>
</textarea>
</td>
</tr>
<tr>
<td colspan=2 style="text-align: center">
<input type=submit name="submit1" value="Leave me a message">
</td>
</tr>
</table>
</form> <!-- MISSING !! -->
</div>
</div>
Related
This is the code for the admin panel of a certain site. Appointments asked by customers will be shown in this page. The admin will be able to change the appointments based on availability.
<?php
while($row = mysqli_fetch_assoc($result)){
?>
<form action="adminEdit.php" method="POST">
<tr>
<td><input type="text" id="name" value="<?php echo $row['Name'];?>"></input></td>
<td><input type="text" id="address" value="<?php echo $row['Address'];?>"></input></td>
<td><input type="text" id="phone" value="<?php echo $row['Phone'];?>"></input></td>
<td><input type="text" id="license" value="<?php echo $row['Car_License_No'];?>"></input></td>
<td><input type="text" id="engine" value="<?php echo $row['Car_Engine_No'];?>"></input></td>
<td><input type="text" id="date" value="<?php echo $row['Date'];?>"></input></td>
<td><input type="text" id="mechanic" value="<?php echo $row['Mechanic'];?>"></input></td>
<td><input type="submit" name="submit" value="Change"/></td>
</tr>
</form>
<?php
}
?>
Here, each row of data has a corresponding button which will be used for changing or modifying the records of that particular row. Once the admin changes a specific appointment it should get updated in database.
My problem is, all the rows are getting generated by a while loop. Now how can I access a specific row when the change button of that specific row has been clicked ? As the rows are getting generated by a loop, I wont be able to access them bynameoridbecause all of them will have the samenameandid`.
Searched for relevant questions but none of them matched with my scenario. It will be of great help getting an answer. Thanks in advance.
Personally I'd be inclined to take the output from being in the loop for better control over the data and resolving the issue. You're also creating a new form on each loop.
Just loop the DB and create a new variable, then use that variable to output the data in the form.
Example code to show the basic idea, not tested or stating it's complete etc:
while ($row = mysqli_fetch_assoc($result)) {
$someNewVar[$row['id']] = $row;
// The 'id' index would be from DB which identifies individual rows
}
?>
<form action="adminEdit.php" method="POST">
<?php
foreach ($someNewVar as $index => $value) {
?>
<tr>
<td>
<input
type="text"
id="<?php echo $index;?>"
value="<?php echo $value['Name'];?>">
</input>
</td>
<td>
<input
type="submit"
name="submit"
value="Change"/>
</td>
</tr>
<?php
}
?>
</form>
Then you'd need to have the row ID passed from clicking the submit button.
On a side note, this whole approach could be tidied up, and data should be obtained in one file separate to where you output it.
Then in the file which obtains the data you can set the array to something which is also identified in the output file to manage if no data was obtained.
ie
getData.php
while ($row = mysqli_fetch_assoc($result)) {
$dataFromDb[$row['id']] = $row;
}
$someNewVar = !empty($dataFromDb) ? $dataFromDb : false;
showData.php
if ($someNewVar) {
// do the loop and form
} else {
echo 'sorry no data found';
}
I was wondering how to make a search form where user has 3 options to search with
Search By age (dropdown 18-25 & 26-40)
Search By gender (male or female)
Search By name
In my code, when I click "Submit" with blank fields, it's throwing all data which i don't it to:
<?php
$output = NULL;
if (isset ( $_POST ['submit'] )) {
// Connect to database
$mysqli = new Mysqli ( "localhost", "root", "2222", "matrimonialPortal" );
$search = $mysqli->real_escape_string ( $_POST ['search'] );
// Query the databse
$resultSet = $mysqli->query ( "SELECT * FROM mp_user WHERE name LIKE '%$search%' OR email LIKE '%$search%' OR salutation LIKE '%$search%' OR id LIKE '%$search%'" );
if ($resultSet->num_rows > 0) {
while ( $rows = $resultSet->fetch_assoc () ) {
$name = $rows ['name'];
$email = $rows ['email'];
$output .= "::<strong>The Details of your search</strong> ::<br /> Name: $name<br /> Email:$email<br /><br /> ";
}
} else {
$output = "Oops No results Found!!";
}
}
?>
<!-- The HTML PART -->
<form method="POST">
<div>
<p>
Search By name: <input type="TEXT" name="search" /> <input
type="SUBMIT" name="submit" value="Search >>" />
</p>
</div>
<div>Search By Age :
<select name="age">
<option></option>
<option value="18-20">18-20</option>
<option value="20-25">20-25</option>
</select><input type="SUBMIT" name="submit" value="Search >>" />
</div>
<br />
<div>
Search By Gender:
<select name="salutation">
<option></option>
<option value="0">--- Male ---</option>
<option value="1">--- Female ---</option>
</select> <input type="SUBMIT" name="submit" value="Search >>" />
</div>
<br> <br>
</form>
<?php echo $output; ?>
It seems like you are new to PHP. Here is a solution for you.
First HTML PART. Here use "action" which means that the page will locate the file and process data. For example action="search_process.php". But if you are processing the data from the same page use $_SERVER['PHP_SELF'];
<!-- The HTML PART -->
<form method="POST" action="$_SERVER['PHP_SELF']"> // here it will load the self page
<div>
<p>
Search By name: <input type="text" name="search_name" />
Search By age: <input type="text" name="search_age" />
Search By gender: <input type="TEXT" name="search_gender" />
<input type="submit" name="submit_name" value="Search >>" />
</p>
</div>
Now the PHP part:
<?php
if(isset($_POST['submit_name'])
{
//What happens after you submit? We will now take all the values you submit in variables
$name = (!empty($_POST['search_name']))?mysql_real_escape_string($_POST['search_name']):null; //NOTE: DO NOT JUST USE $name = $_POST['search_name'] as it will give undefined index error (though your data will be processed) and will also be open to SQL injections. To avoid SQL injections user mysql_real_escape_string.
$age = (!empty($_POST['search_age']))?mysql_real_escape_string($_POST['search_age']):null;
$gender = (!empty($_POST['search_gender']))?mysql_real_escape_string($_POST['search_gender']):null;
//Now we will match these values with the data in the database
$abc = "SELECT * FROM table_name WHERE field_name LIKE '".$name."' or field_gender LIKE '".$gender."' or field_age LIKE '".$age."'"; // USE "or" IF YOU WANT TO GET SEARCH RESULT IF ANY OF THE THREE FIELD MATCHES. IF YOU WANT TO GET SEARCH RESULT ONLY WHEN ALL THE FIELD MATCHES THEN REPLACE "or" with "and"
$def = mysql_query($abc) or die(mysql_error())// always use "or die(mysql_error())". This will return any error that your script may encounter
//NOW THAT WE HAVE GOT THE VALUES AND SEARCHED THEM WE WILL NOW SHOW THE RESULT IN A TABLE
?>
<table cellspacing="0" cellpadding="0" border"0">
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
</tr>
<?php while($row = mysql_fetch_array($def)) { // I HAD MISSED OUT A WHILE LOOP HERE. SO I AM EDITING IT HERE. YOU NEED TO USE A WHILE LOOP TO DISPLAY THE DATA THAT YOU GOT AFTER SEARCHING.
<tr>
<td><?php echo $row[field_name]; ?></td>
<td><?php echo $row[field_age]; ?></td>
<td><?php echo $row[field_gender]; ?></td>
</tr>
<?php } ?>
</table>
<?php } ?>
A perfect solution for your query. All the best.
Well i cant give you the whole code, but here are the few solutions..
Use 3 different forms with 3 different submit buttons.
Use radio buttons on html form, and make a check on PHP side and perform operations depending upon what or which radio is selected.
Use a button instead of submit, radio buttons, hidden fields, and pass data to different php page on form submit (this can be lengthy).
Well you have options.
You can replace your code
if ($resultSet->num_rows > 0) {
with this
if ($resultSet->num_rows > 0 and trim($search) != "") {
so it will not show all results if your input box is empty
hope this will help you
Edit
here is an example you can get idea
$qry = "SELECT * FROM test WHERE 1=1";
if($purpose!="")
$qry .= " AND purpose='$purpose'";
if($location!="")
$qry .= " AND location='$location'";
if($type!="")
$qry .= " AND type='$type'";
and for age
if ($age!='') {
$qry .= " AND age between ".str_replace('-',' and ',$age);
}
When you POST a blank variable and Query with %$search% and 'OR' other criteria, sql matches all records with space in column Name ! So you will have to use some variation of;
If(empty($POST['search']){ ['Query witbout Name parameter']} else{['Query with Name parameter']}
As for converting DOB to match age range. You will have to use
SELECT TIMESTAMPDIFF
answered here
calculate age based on date of birth
I'm having some difficulty with php forms.
I have created a page called 'post_details.php' (this simply displays a photo of a product & description). Each product has a unique id
Within posts_details.php, I have used to include command to include a form. This form allows users to send me feedback regarding the product.
For some reason the form is not workin. Everytime the submit button is clicked, the alert box warns me that I need to complete the form (even if the form is complete)
The last part of line one doesn't seem to work. It's not picking up the post_id
Can anyone please help ??
post a comment
<form method="post" action="post_details.php?post= <?php echo $post_id; ?>">
<table width "600">
<tr>
<td>Your email:</td>
<td><input type="text" name="comment_email"/></td>
</tr>
<tr>
<td>Your Comment:</td>
<td><textarea name="comment" cols="35" rows="16"/></textarea></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="postcom"/></td>
</tr>
</table>
</form>
<?php
if(isset($_POST['comment'] )) {
$comment_email = $POST['comment_email'];
$comment = $POST['comment'];
if( $comment_email=='' OR $comment=='') {
echo "<script>alert('Please complete form')</script>";
echo "<script>window.open('post_details.php?post=post_id')</script>";
exit();
}
else {
echo "complete";
}
}
?>
You have error here
if(isset($_POST['comment'] )) {
$comment_email = $POST['comment_email'];
^
$comment = $POST['comment'];
^
....
Instead of $POST it must be $_POST['comment_email'] and $_POST['comment']
I have a form that will be loaded into a div on another page through AJAX. On click, I would like to check required fields for content. If required fields are not populated, I want to put a message next to the field like in this example: http://www.w3schools.com/php/php_form_required.asp.
If name were required for example, here I would like to add
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{$name=$_POST['name'];}
On Submit:
<html>
<body>
<?php
// Connect to DB
XXX
$phone=$_POST['phone'];
$category=$_POST['category'];
implode(',',$_POST['check']);
//or something like
$checkstring="";
foreach($_POST['check'] as $checkboxes) {
$checkstring.= $checkboxes .",";
}
$c = rtrim($checkstring);
$query = "INSERT INTO contact VALUES ('$name','$phone', '$c', '$category')";
mysql_query($query) or die('Error, insert query failed');
echo "Hi! $name. Your phone number <b> $phone </b> is in our database";
?>
</body>
</html>
And here I would add
<?php echo $nameErr;?>
next to the name field.
But when I put
?>
in the php variable, it breaks up the variable because it thinks I am ending the
<?php
at the top of Form.
Form:
<?php
// Get value of clicked button
$button = $_GET['button'];
$test = '<center>
<table>
<tr>
<td style="height: 20px;"></td>
</tr>
</table>
<h1>Demo</h1>
<form id="ContactForm" onsubmit="return submitForm();">
<div class="form_result"> </div>
Name: <input name="name" type=text ><br>
Phone: <input name="phone" type=text ><br>
Business Capabilities:<br>
<input type="checkbox" name="check[]" value="c1">C1<br>
<input type="checkbox" name="check[]" value="c2">C2<br>
<select name="category">Category:
<option value="d1">D1</option>
<option value="d2">D2</option>
<option value="d3">D3</option>
</select><br>
<input type="submit" >
</form>
</center>
';
print json_encode($test);
?>
Is it possible for me to put that php statement in the php variable? Or is there another way that would be cleaner to do this? Thanks for your help.
You don't need to echo it. You're creating a giant HTML string, just use string concatenation to include your error:
$test = 'blah blah blah '.$nameErr.' blah blah blah';
Before you go any further though, stop and learn about prepared statements - what you're currently doing with your database is very dangerous, and highly susceptible to sql injection attacks. http://www.php.net/manual/en/book.pdo.php
After a long night, I don't have the complete effort to use your code (so I apologize). But I should be able to get you on the right track. I suggest using JSON as a response in your submit.php page that is called by AJAX. So for example, your script could have:
if(empty($_POST["name"])) {
echo json_encode(array(
'error' => 'Name is required.'
));
} else {
// Do form stuff here
echo json_encode(array(
'phone' => $phone
));
}
Then in your AJAX call, you can easily handle your JSON (in a more modular way, allowing you to easily change your responses/layout).
$.ajax('submit.php', {
// Settings
dataType: 'json' // We want JSON response, this will parse it as an object
}).done(function(data) {
if(data.error !== 'undefined') {
alert('Error: ' + data.error);
} else {
alert('Your phone number is ' + data.phone);
}
});
Feel free to ask if you need more explanation on what I am doing here.
I am trying to set up errors to pop up if they do not fill in the form section. The Name and email portion portion work when I hit submit but the comment section does not. I noticed when I start to type into the comment section it starts over about 5 spaces in so it looks like there is something in the field. Once I delete that and submit the form the error message appears in the comment section not to the right of the field like the 2 fields above? Help please?
<!DOCTYPE html>
<html>
<head>
<title>My Guestbook</title>
<style type="text/css">
.errors { color: ff0000; }
</style>
</head>
<body>
<?php /* Opening tag of php */
//initialize error array
$errors=array();
//main logic
if(isset($_REQUEST['submit'])){
checkForm();
}
else{
printForm();
}
//begin functions
function checkForm()
{
global $errors;
if($_POST[name] == "")
$errors['name']="<span class=\"errors\"><b>  Please, enter your Name!</span>";
if($_POST[email] == "")
$errors['email']="<span class=\"errors\"><b>  Please, enter your Email!</span>";
if($_POST[myComments] == "")
$errors['myComments']="<span class=\"errors\"><b>  Please, enter something! </span>";
if(count($errors) !=0)
printForm();
else
confirm();
} //end checkForm function
function confirm(){
print "<h2>Thank you for signing my guestbook</h2>";
print "<p>Name: ".$_POST['name'];
print "</p><p>Email: ".$_POST['email'];
print "</p><p>Comment: ".$_POST['myComments'];
print "</p><br />"; //Extra line break.
print "<em>Today is " . date('F jS, Y.')."</em><br />"; //Extra line break.
} //end confirm
function printForm()
{
global $errors;
$place = $_POST[place];
// My old code I am trying to combine
print <<< HERE
<h1>Please sign my guestbook.</h1>
<form method="POST" action="{$_SERVER['PHP_SELF']}">
<table>
<tr>
<td class=name </td>Name: <br />
<td><input type="text" name="name" id="name" value="{$_POST['name']}">
{$errors['name']}</td>
</tr>
<tr>
<td class=email</td>Email: <br />
<td><input type="text" name="email" id="email" value"{$_POST['email']}">
{$errors['email']}</td>
</tr>
<tr>
<td class=myComments</td>Comments:<br />
<td><textarea type="text" name="myComments" id="mycomments" rows="4" cols="40" value" {$_POST['myComments']}">
{$errors['myComments']}</textarea></td>
</tr>
<tr>
<td> </td>
<td><input type=submit name="submit" value="send"><input type="reset" name="clear" value=Clear> </td>
</tr>
</table>
</form>
<br>
HERE;
print "Today is " . date('F jS, Y.')."<br>"; //Date printed in page below form.
print "Form designed by Kevin O'Leary "."<br>"; //Date printed in page below form.
}
?>
</body>
</html>
TextArea doesn't have a value or type attribute (and even if it did, you don't have an equal sign after value). Any spaces (line breaks, space, tabs, etc) between the TextArea and /TextArea will show up, so don't do a line break between the opening and closing tags.
You probably want your TextArea markup to look something like this:
<textarea name="myComments" id="mycomments" rows="4" cols="40">{$_POST['myComments']}</textarea> {$errors['myComments']}
This will cause the $_POST['myComments'] to show up in the TextArea, and $errors['myComments'] to show to the right of the textarea (or below, if the textarea is too wide and it causes it to wrap).
Also, your email field doesn't have an equal sign after value, either.
Take a look at this for more information on textarea usage: https://developer.mozilla.org/en-US/docs/HTML/HTML_Elements/textarea