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
Related
I have created a simple HTML form containing just one field. When I press submit some PHP code that I have written gets called and outputs text that would include submitted data if everything was working. But no submitted text gets printed by the PHP. The form has been created on a Godaddy HTML page and the form is as follows:
<FORM BORDER="1" action="http://www.bestpro.com.au/wordpress/PHB_action.php"
method="post" enctype="application/x-www-form-urlencoded"
eenctype="multipart/form-data" name="PHBForm" accept-charset="ISO-8859-1"
ienctype="text/plain">
<TABLE>
<TR>
<TD>First name:</TD><TD><INPUT type="text" name="firstname" id="firstname"></TD>
<TD></TD><TD></TD>
<TD> </TD><TD> </TD>
</TR>
<TR>
<TD> </TD><TD> </TD>
<TD> </TD><TD></TD>
<TD> </TD><TD><input type="submit" value="Submit"></TD>
</TABLE>
</FORM>
The PHP code output starts as follows:
This is where we end up.
Using `$_POST["firstname"]` which outputs nothing.
Using `htmlspecialchars($_POST["firstname"])` which also outputs nothing.
Question:
The PHP output doesn't include the value that I entered into the field.
Can anyone see what I am doing incorrectly?
I see nothing wrong here, so I can only assume it is something wrong with how you output it on your PHB_action.php page.
You say that you're placing $_POST['firstname'] on your page, but have you actually made sure to echo or print it to the page?
You can do this like so:
echo $firstname = $_POST['firstname']; // notice the echo placed before
or
$firstname = $_POST['firstname'];
print("$firstname");
EDIT:
I've notice you have put your post data inside of single quotation marks when echoing out to your page.
You must concatenate on your data rather than putting them inside of single quotes when echoing, like so:
echo 'Using' . $_POST['firstname']; // notice the dot in between the string and the post data.
Either that, or you have not installed PHP correctly (or at all) onto your server.
Hope this helps
So, this is pretty straight forward and I have written it up and will explain each bit as i go.
The PHP you need for this is:
<?php
if (isset($_POST['send']))
{
$fname = $_POST['firstName'];
if (!empty($fname))
{
echo "hello $fname";
} else {
echo "Please supply your first name.";
}
}
?>
$_POST['send'] is the name of your submit button, this will be the trigger for your PHP to initiate and run through the rest of the code.
$fname = $_POST['firstName']
This is just where I prefer to store the $_POST as a variable in the event you are going to re use it again it saves time writing the entire thing.
if(!empty)
if the username isn't empty (!empty meaning not empty) then perform the echo of $fname. however if it comes back as empty it will echo the else echo "please supply...;
Now for the form.
<form action="" method="post">
<table>
<tr>
<td>First Name:</td>
<td><input type="text" name="firstName"></td>
</tr>
<tr>
<td><input type="submit" name="send"></td>
</tr>
</table>
</form>
Just a straight forward form with a blank action on mine (I prefer to keep the PHP within the same file however I normally relay it back to a Class within a different file.
Each form input (First Name / Submit) must have a name="" value otherwise the PHP cannot read it and run with it.
I hope this makes sense and isn't too puzzling :)
Your input field should be inside tag and method should be post. Like:
<html>
<body>
<Form method=post>
<input id=mytextfield name=mytextfield type=text />
<input type=submit value=Submit />
</Form>
</body>
</html>
this is probaly an easy one, but I just cant seem to figure it out. I've tried googling for this aswell, but without any luck to my particular problem...
What I want, is that the radio selection gets remembered two times (kinda), it remembers after the first time I click submit. But when I click submit again on my next page, it wont remember the value.
Well, I want all the information stored in my database pretty much..
Thanks!
EDIT 1: Oh yeah, the thing that does not go into my database is "valgt_skap" or in other words "radios", everthing else works fine.
Bokssvar.php
<html>
<head>
<link rel="stylesheet" type="text/css" href="style2.css?<?php echo time(); ?>" />
<title>Registrering</title>
</head>
<body>
<?php
if(isset($_SESSION['boxfeil'])) echo $_SESSION['boxfeil'];
unset($_SESSION['boxfeil']);
?>
<form action="bestilt.php" method="post" name="inputform_Field">
<table id="valgt_skap_tabell" class="bokssvartabell">
<tr>
<td>Valgt skap</td>
</tr>
<tr>
<td>
<input class="bokssvarskjema" type="text" name="valgt_skap" disabled value= <?php
if(isset(($_POST['radios']))){
echo ($_POST['radios']);
} else {
header('location: index.php');
} ?>>
</td>
</tr>
</table>
<table id="opplysninger_tabell" class="bokssvartabell">
<tr>
<td>Fornavn:</td>
<td>Etternavn:</td>
<td>Telefon:</td>
<td>E-post:</td>
<td>Elev Nummer:</td>
</tr>
<tr>
<td><input type="text" name="Fornavn_nm" id="fornavn_check"></td>
<td><input type="text" name="Etternavn_nm" id="etternavn_check"></td>
<td><input type="text" name="Telefon_nm" id="telefon_check" maxlength=8></td>
<td><input type="text" name="E-post_nm" id="epost_check"></td>
<td><input type="text" name="Elevnummer_nm" id="elevnr_check"></td>
</tr>
</table>
<div style="text-align:center;">
<button id="bestill_skap" type="submit" name="bestill_Skap">Bestill skap</button>
</div>
</form>
</body>
bestilt.php
<?php
require 'connectdb.php';
$inputFornavn_check = $_POST['Fornavn_nm'];
$inputEtternavn_check = $_POST['Etternavn_nm'];
$inputTelefon_check = $_POST['Telefon_nm'];
$inputEpost_check = $_POST['E-post_nm'];
$inputElevnr_check = $_POST['Elevnummer_nm'];
$inputSkap_check = $_POST['valgt_skap'];
$insertInfo_query = "INSERT INTO elever (Fornavn, Etternavn, Telefon, Epost, ElevNr, Skap)
VALUES ('$inputFornavn_check' , '$inputEtternavn_check' , '$inputTelefon_check' , '$inputEpost_check' , '$inputElevnr_check' , '$inputSkap_check')";
$connect_DB->query($insertInfo_query);
?>
Try using sessions to store the value. First use session_start(), then store in $_session['fieldname']=value. Then you can use it in the preceding pages.
On the second page, receive the value and put it on a hidden form element.
<form>
...
<input type="hidden" name="valgt_skap" value="$radioValue">
...
</form>
This element is not shown on the page, although it's present and submited with the form.
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>
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 want to do a 'pop up image' using javascript to display a simple user guide image, after the user click on search the image will pop up, to give them a better understanding of the results. So when the user close the image they will be link to results.php. Sorry that I can't provide any useful javascript codes, because those codes that I've found from the internet is too long. And I'm very noob at javascript.
Save Post->Session
<?php
$loan_amt = $_POST['loan_amt'];
if($_POST['search']){
if($_POST['loan_amt']=="" || $_POST['loan_tenure']==""){
$error = "Please fill up the mandatory fields";
}else{
session_start();
$_SESSION['property_type'] = $_POST['property_type'];
$_SESSION['property_status'] = $_POST['property_status'];
$_SESSION['loan_amt'] = $_POST['loan_amt'];
$_SESSION['loan_tenure'] = $_POST['loan_tenure'];
header("location:rates_result.php");
}
}
?>
Search Form (loan amount field)
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" onsubmit="this.loan_amt.value=this.loan_amt.value.replace(/\,/g,'')">
<table width="400px">
<tr>
<td class="color1" width="130">Loan Amt (SGD)*:</td>
<td width="258" align="left">
<input type="text" style="width:150px;font-size:16px" onkeyup="format(this)" onchange="format(this)"
onblur="if(this.value.indexOf('.')==-1)this.value=this.value" name="loan_amt">
</td>
<td width="258" align="left"><input type="submit" class="buttonStyle" name="search" value="search" /></td>
</tr>
</table>
</form>
in the popup page you can put in section:
<script type="text/javascript">
window.onclose=goToResults
function goToResults(){
//do the parent go to results.php
parent.location="results.php";
}
</script>
if its a form to be submitted you can point a function on parent and that function can submit the form:
in popup:
function goToResults(){
//do the parent go to results.php
parent.submitForm();
}
in page:
function sumbitForm(){
form_to_submit=document.getElementById("FORM_ID");
form_to_submit.submit();
}