<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input onclick="this.value=''" type="text" name="first_name" value="First Name">
<input onclick="this.value=''" type="text" name="last_name" value="Last Name">
<input onclick="this.value=''" type="text" name="pwd" value="The Passcode">
<input name="submit" type="submit" value="Submit" class="submit_">
<textarea name="comments" id="comments" rows="4" cols="50"></textarea>
</form>
PHP :
if(isset($_POST['submit']))
{
$name = mysql_real_escape_string($_POST['first_name']);
$pwd = mysql_real_escape_string($_POST['pwd']);
$text = mysql_real_escape_string($_POST['comments']);
// print_r($_POST);
if(is_null($text)) {
debug_to_console('some fields empty');
echo "<p class=\"warning\">* Your Message Did Not Contain Any Characters.</p>";
}
else if($name === 'First Name'){
debug_to_console('name isnt set');
echo "<p class=\"warning\">* You Have Not Entered Your First Name Correctly.</p>";
}
else if($pwd !== 'XyZ'){
debug_to_console('password not set');
echo "<p class=\"warning\">* Passcodes Do Not Match.</p>";
} else {
Keeps returning 'password not set' even though the form input matches the variable. Used print_r and $pwd states XyZ.
tried removing onClick from the form input. I'm assuming this is a caps thing?
Please help, thank you.
Check $pwd with
var_dump($pwd);
I do believe $pwd is a string (because you use !== instead of !=) AND doesn't contain: XyZ
(if you didn't change the value in input field pwd, its value is still: The Passcode)
Related
I am making a simple Form the problem i am facing is when i submit the form values still remains in the field. and I want to clear it after SUCCESSFUL submission. Please help.
here is my code for the form..
<label class="w">Plan :</label>
<select autofocus="" name="plan" required="required">
<option value="">Select One</option>
<option value="FREE Account">FREE Account</option>
<option value="Premium Account Monthly">Premium Account Monthly</option>
<option value="Premium Account Yearly">Premium Account Yearly</option>
</select>
<br>
<label class="w">First Name :</label><input name="firstname" type="text" placeholder="First Name" required="required" value="<?php echo $_POST['firstname'];?>"><br>
<label class="w">Last Name :</label><input name="lastname" type="text" placeholder="Last Name" required="required" value="<?php echo $_POST['lastname'];?>"><br>
<label class="w">E-mail ID :</label><input name="email" type="email" placeholder="Enter Email" required="required" value="<?php echo $_POST['email'];?>"><br>
<label class="w">Password :</label><input name="password" type="password" placeholder="********" required="required" value="<?php echo $_POST['password'];?>"><br>
<label class="w">Re-Enter Password :</label><input name="confirmpassword" type="password" placeholder="********" required="required" value="<?php echo $_POST['confirmpassword'];?>"><br>
<label class="w">Street Address 1 :</label><input name="strtadd1" type="text" placeholder="street address first" required="required" value="<?php echo $_POST['strtadd1'];?>"><br>
<label class="w">Street Address 2 :</label><input name="strtadd2" type="text" placeholder="street address second" value="<?php echo $_POST['strtadd2'];?>"><br>
<label class="w">City :</label><input name="city" type="text" placeholder="City" required="required" value="<?php echo $_POST['firstname'];?>"><br>
<label class="w">Country :</label><select autofocus="" id="a1_txtBox1" name="country" required="required" placeholder="select one" value="<?php echo $_POST['country'];?>">
Any help would be appriciated
They remain in the fields because you are explicitly telling PHP to fill the form with the submitted data.
<input name="firstname" type="text" placeholder="First Name" required="required"
value="<?php echo $_POST['firstname'];?>">
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ HERE
Just remove this, or if you want a condition to not do so make a if statement to that echo or just cleanup the $_POST fields.
$_POST = array(); // lets pretend nothing was posted
Or, if successful, redirect the user to another page:
header("Location: success.html");
exit; // Location header is set, pointless to send HTML, stop the script
Which by the way is the prefered method. If you keep the user in a page that was reached through a POST method, if he refreshes the page the form will be submitted again.
You can use .reset() on your form.
$(".myform")[0].reset();
I was facing this similiar problem and did not want to use header() to redirect to another page.
Solution:
Use $_POST = array(); to reset the $_POST array at the top of the form, along with the code used to process the form.
The error or success messages can be conditionally added after the form.
Hope this helps :)
Here is the solution for when the for is submitted with the successful message all form fields to get cleared. for that set the values equals to false check the code below
<?php
$result_success = '';
$result_error = '';
$full_Name_error = $email_error = $msg_error = '';
$full_Name = $email = $msg = $phoneNumber = '';
$full_Name_test = $email_test = $msg_test = '';
//when the form is submitted POST Method and must be clicked on submit button
if ($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['form-submit'])) {
$full_Name = $_POST['fullName'];
$email = $_POST['email'];
$phoneNumber = $_POST['phoneNumber'];
$msg = $_POST['message'];
// Form Validation for fullname
if (empty($full_Name)) {
$full_Name_error = "Name is required";
} else {
$full_Name_test = test_input($full_Name);
if (!preg_match("/^[a-z A-Z]*$/", $full_Name_test)) {
$full_Name_error = "Only letters and white spaces are allowed";
}
}
//Form Validation for email
if (empty($email)) {
$email_error = "Email is required";
} else {
$email_test = test_input($email);
if (!filter_var($email_test, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid Email format";
}
}
//Form Validation for message
if (empty($msg)) {
$msg_error = "Say atleast Hello!";
} else {
$msg_test = test_input($msg);
}
if ($full_Name_error == '' and $email_error == '' and $msg_error == '') {
// Here starts PHP Mailer
date_default_timezone_set('Etc/UTC');
// Edit this path if PHPMailer is in a different location.
require './PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
/*Server Configuration*/
$mail->Host = 'smtp.gmail.com'; // Which SMTP server to use.
$mail->Port = 587; // Which port to use, 587 is the default port for TLS security.
$mail->SMTPSecure = 'tls'; // Which security method to use. TLS is most secure.
$mail->SMTPAuth = true; // Whether you need to login. This is almost always required.
$mail->Username = ""; // Your Gmail address.
$mail->Password = ""; // Your Gmail login password or App Specific Password.
/*Message Configuration*/
$mail->setFrom($email, $full_Name); // Set the sender of the message.
$mail->addAddress(''); // Set the recipient of the message.
$mail->Subject = 'Contact form submission from your Website'; // The subject of the message
/*Message Content - Choose simple text or HTML email*/
$mail->isHTML(true);
// Choose to send either a simple text email...
$mail->Body = 'Name: ' . $full_Name . '<br>' . 'PhoneNumber: ' . $phoneNumber . '<br>' . 'Email: ' . $email . '<br><br>' . 'Message: ' . '<h4>' . $msg . '</h4>'; // Set a plain text body.
// ... or send an email with HTML.
//$mail->msgHTML(file_get_contents('contents.html'));
// Optional when using HTML: Set an alternative plain text message for email clients who prefer that.
//$mail->AltBody = 'This is a plain-text message body';
// Optional: attach a file
//$mail->addAttachment('images/phpmailer_mini.png');
if ($mail->send()) {
$result_success = "Your message was sent successfully! " .
//Here is the solution for when the for is submitted with the successful message all form fields to get cleared.
$full_Name;
$full_Name = false;
$email = false;
$phoneNumber = false;
$msg = false;
} else {
$result_error = "Something went wrong. Check your Network connection and Please try again.";
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
The POST data which holds the submitted form data is being echoed in the form, eg:
<input name="firstname" type="text" placeholder="First Name" required="required"
value="<?php echo $_POST['firstname'];?>"
Either clear the POST data once you have done with the form - ie all inputs were ok and you have actioned whatever your result from a form is.
Or, once you have determined the form is ok and have actioned whatever you action from the form, redirect the user to a new page to say "all done, thanks" etc.
header('Location: thanks.php');
exit();
This stops the POST data being present, it's know as "Post/Redirect/Get":
http://en.wikipedia.org/wiki/Post/Redirect/Get
The Post/Redirect/Get (PRG) method and using another page also ensures that if users click browser refresh, or back button having navigated somewhere else, your form is not submitted again.
This means if your form inserts into a database, or emails someone (etc), without the PRG method the values will (likely) be inserted/emailed every time they click refresh or revisit the page using their history/back button.
Put the onClick function in the button submit:
<input type="text" id="firstname">
<input type="text" id="lastname">
<input type="submit" value="Submit" onClick="clearform();" />
In the <head>, define the function clearform(), and set the textbox value to "":
function clearform()
{
document.getElementById("firstname").value=""; //don't forget to set the textbox id
document.getElementById("lastname").value="";
}
This way the textbox will be cleared when you click the submit button.
I was just trying to fix same error, I finally fixed it, so I will copy to you part of the code, maybe it helps you.
<input type="text" name="usu" id="usu" value="<?php echo $usu;?>" ></input>
<input type="text" name="pass" id="pass" value="<?php echo $varpass;?>"></input>
those are the inputs I wanted to clean after pressing my button.
And here php code:
$query= "INSERT INTO usuarios (tipo, usuario, password) VALUES ('".$vartipo."', '".$usu."', '".$varpass."')";
if (!mysqli_query($conexion,$query)){
die('Error: ' . mysqli_error($conexion));
}
else{
$usu = '';
$varpass= '';
$result = '<div class="result_ok">El usuario se ha registrado con éxito! <div>';
}
$usu = '';
$varpass= '';
those are the lines that cleans the inputs :D
this code will help you
if($insert){$_POST['name']="";$_POST['content']=""}
If you want your form's field clear, you must only add a delay in the onClick event like:
<input name="submit" id="MyButton" type="submit" class="btn-lg" value="ClickMe" onClick="setTimeout('clearform()', 2000 );"
onClick="setTimeout('clearform()', 1500 );" . in 1,5 seconds its clear
document.getElementById("name").value = ""; <<<<<<just correct this
document.getElementById("telephone").value = ""; <<<<<correct this
By clearform(), I mean your clearing-fields function.
// This file is PHP.
<html>
<?php
if ($_POST['submit']) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$confirmpassword = $_POST['confirmpassword'];
$strtadd1 = $_POST['strtadd1'];
$strtadd2 = $_POST['strtadd2'];
$city = $_POST['city'];
$country = $_POST['country'];
$success = '';
// Upon Success.
if ($firstname != '' && $lastname != '' && $email != '' && $password != '' && $confirmpassword != '' && $strtadd1 != '' && $strtadd2 != '' && $city != '' && $country != '') {
// Change $success variable from an empty string.
$success = 'success';
// Insert whatever you want to do upon success.
} else {
// Upon Failure.
echo '<p class="error">Fill in all fields.</p>';
// Set $success variable to an empty string.
$success = '';
}
}
?>
<form method="POST" action="#">
<label class="w">Plan :</label>
<select autofocus="" name="plan" required="required">
<option value="">Select One</option>
<option value="FREE Account">FREE Account</option>
<option value="Premium Account Monthly">Premium Account Monthly</option>
<option value="Premium Account Yearly">Premium Account Yearly</option>
</select>
<br>
<label class="w">First Name :</label><input name="firstname" type="text" placeholder="First Name" required="required" value="<?php if (isset($firstname) && $success == '') {echo $firstname;} ?>"><br>
<label class="w">Last Name :</label><input name="lastname" type="text" placeholder="Last Name" required="required" value="<?php if (isset($lastname) && $success == '') {echo $lastname;} ?>"><br>
<label class="w">E-mail ID :</label><input name="email" type="email" placeholder="Enter Email" required="required" value="<?php if (isset($email) && $success == '') {echo $email;} ?>"><br>
<label class="w">Password :</label><input name="password" type="password" placeholder="********" required="required" value="<?php if (isset($password) && $success == '') {echo $password;} ?>"><br>
<label class="w">Re-Enter Password :</label><input name="confirmpassword" type="password" placeholder="********" required="required" value="<?php if (isset($confirmpassword) && $success == '') {echo $confirmpassword;} ?>"><br>
<label class="w">Street Address 1 :</label><input name="strtadd1" type="text" placeholder="street address first" required="required" value="<?php if (isset($strtadd1) && $success == '') {echo $strtadd1;} ?>"><br>
<label class="w">Street Address 2 :</label><input name="strtadd2" type="text" placeholder="street address second" value="<?php if (isset($strtadd2) && $success == '') {echo $strtadd2;} ?>"><br>
<label class="w">City :</label><input name="city" type="text" placeholder="City" required="required" value="<?php if (isset($city) && $success == '') {echo $city;} ?>"><br>
<label class="w">Country :</label><select autofocus="" id="a1_txtBox1" name="country" required="required" placeholder="select one" value="<?php if (isset($country) && $success == '') {echo $country;} ?>">
<input type="submit" name="submit">
</form>
</html>
Use value="<?php if (isset($firstname) && $success == '') {echo $firstname;} ?>"
You'll then have to create the $success variable--as I did in my example.
You can check this also
<form id="form1" method="post">
<label class="w">Plan :</label>
<select autofocus="" name="plan" required="required">
<option value="">Select One</option>
<option value="FREE Account">FREE Account</option>
<option value="Premium Account Monthly">Premium Account Monthly</option>
<option value="Premium Account Yearly">Premium Account Yearly</option>
</select>
<br>
<label class="w">First Name :</label><input name="firstname" type="text" placeholder="First Name" required="required" ><br>
<label class="w">Last Name :</label><input name="lastname" type="text" placeholder="Last Name" required="required" ><br>
<label class="w">E-mail ID :</label><input name="email" type="email" placeholder="Enter Email" required="required" ><br>
<label class="w">Password :</label><input name="password" type="password" placeholder="********" required="required"><br>
<label class="w">Re-Enter Password :</label><input name="confirmpassword" type="password" placeholder="********" required="required"><br>
<label class="w">Street Address 1 :</label><input name="strtadd1" type="text" placeholder="street address first" required="required"><br>
<label class="w">Street Address 2 :</label><input name="strtadd2" type="text" placeholder="street address second" ><br>
<label class="w">City :</label>
<input name="city" type="text" placeholder="City" required="required"><br>
<label class="w">Country :</label>
<select autofocus id="a1_txtBox1" name="country" required="required" placeholder="select one">
<option>Select One</option>
<option>UK</option>
<option>US</option>
</select>
<br>
<br>
<input type="reset" value="Submit" />
</form>
After submitting the post you can redirect using inline javascript like below:
echo '<script language="javascript">window.location.href=""</script>';
I use this code all the time to clear form data and reload the current form. The empty href reloads the current page in a reset mode.
You can also use unset function to do this e.g. below is my code where I verify an email existence.
if($mail->check($email)){
$status = 'succ';
$statusMsg = 'Given email <'.$email.'> exists!';
unset($_REQUEST["name"]);
unset($_REQUEST["email"]);
unset($_REQUEST["comment"]);
}elseif(verifyEmail::validate($email)){
$status = 'err';
$statusMsg = 'Given email <'.$email.'> is valid, but does not exist!';
}else{
$status = 'err';
$statusMsg = 'Given email <'.$email.'> is not valid, not exist!';
}
}else{
$status = 'err';
$statusMsg = 'Enter the email address that is to be verified';
}
This can be used after the mysql command of Insert a record in the table and that does it. It resets the values entered there in the fields.
It is possible to ask a browser not to follow the redirect headers, in this case a user can still refresh the page.
I think the best solution is to destroy all the data sent by the form, then attempt to redirect the user to another page.
<?php
// Destroys data _POST
foreach ($_POST as $key => $value) {
unset($_POST[$key]);
}
// redirect user
header("Location: other_page.html");
// terminate the current script
exit();
I have a simple form to submit testimonials, I also was having trouble clearing the form, what I did was after the query is submitted successfully I and before redirecting to another page I cleared the imputs $name =''; ect. The page submitted and redirected with no errors.
While I found something similar to this question on here it didn't answer my question outright.
I have set up this php script to validate the form data, which works, after its validated I want it to then pass the info onto another script page to let the user then verify their input data and then mail the data. Its at this state that I'm having trouble. I've spent the last few days trying to find a solution to this and unfortunately coming up short.
<?php
$name_error = '';
$email_error = '';
$comments_error = '';
$error = false;
if (!empty($_POST['submitted']))
{ //if submitted, the validate.
$name = trim($_POST['name']);
if (empty($name))
{
$name_error='Name is required';
$error = true;
}
$email = trim($_POST['email']);
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
$email_error='E-mail address not valid';
$error = true;
}
$comments = trim($_POST['comments']);
if (empty($comments))
{
$comments_error='Comments are required';
$error = true;
}
if ($error == false)
{
$name_send = $name;
$email_send = $email;
$comments_send = $comments;
/* Redirect visitor to the thank you page */
header('Location: /mail.php');
exit();
}
}
The form this is attached to:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post">
<label>Your Name</label><br />
<input type="text" name="name" style="width:95%" class="text" value='<?php echo htmlentities($name) ?>' />
<br/>
<span class='error'><?php echo $name_error ?></span>
<br />
<label>Email</label><br />
<input type="email" name="email" style="width:95%" class="text" value='<?php echo htmlentities($email) ?>' />
<br/>
<span class='error'><?php echo $email_error ?></span>
<br />
<label for="comments" style="font-size:16px;">Feedback Comments</label><br />
<textarea name="comments" style="width:95%;" rows="8" value='<?php echo htmlentities($comments) ?>'></textarea>
<br />
<span class='error'><?php echo $comments_error ?></span>
<br />
<input type="checkbox" name="allowCommentPublish" checked="checked" />
<label for="allowCommentPublish" style="font-size:10px;">Allow these comments to be used on our website</label>
<fieldset class="optional">
<h2>[ OPTIONAL ]</h2>
<label>Company Name</label><br />
<input type="text" name="companyName" style="width:95%" class="text" />
<br/>
<label>Phone</label><br />
<input type="text" name="phone" style="width:95%" class="text" /><br/>
<div style="margin:5px 0px;">
<input type="checkbox" name="incmarketing" />
<label style="font-size:10px;"> Yes, you can email me specials and promotions.</label>
<br/>
</div>
</fieldset>
<fieldset>
<input type="submit" name="submitted" value="Send" />
</fieldset>
I will point out im focusing on the main data inputs: Name E-mail and comments.
I need the info from this form to be sent onward but i dont know exactly how to do this and any help will be appreciated greatly.
For passing the values to next page you will have to use either of the three methods.
1. Set cookies with the data.
2. Use global variable session.
3.Pass the data in the url.
For cookies u can set cookies with the values like
setcookie('name',$name);
in ur next page read those cookie data
For sessions:
$_SESSION['name']= $name;
for reading data from cookies & session:
$name = $_COOKIE['name'];
$name = $_SESSION['name'];
For using sessions you must add the line
session_start();
at the start of both the pages that send or receive(use) the data
and for urls
header('Location: /mail.php?name=$name&email=$email&comment=$comments');
Read more on using session
If you need to pass values from one script to another you can use $_SESSION variables. To start a session use: (at the top of the php script)
session_start();
$_SESSION['somename'] = $somevariable;
To access or get that same variable you can use this:
session_start();
$some_other_variable = $_SESSION['somename'];
or you can use hidden input fields.
You can use hidden fields and javascript to submit the form. However as this is the same php page as the original form you will need an if statement
echo '<form name="newForm" action="newpage.php" method="POST">';
echo '<input type="hidden" name="name2" value"' . $name . '">;
echo '<input type="hidden" name="email2" value"' . $email . '">;
echo '<input type="hidden" name="comments2" value"' . $comments . '"></form>;
echo '<script> if (document.getElementById("name2").value != ""){window.onload = function(){ window.document.newForm.submit(); }} </script>';
I'm using kespersy antivirus.I want to store the details in database.but password and confirm password value is not printed while testing.
all the field values are echoed except password and confirm password.$pass is password variable and $c_pass is confirm password variable.
<form name="profile" method="post">
<p style="margin-left:1cm">Name<a style="margin-left:45px"></a> : <input type="text" name="p_name" size=18 maxlength=50></p>
<p style="margin-left:1cm">Email<a style="margin-left:45px"></a> : <input type="text" name="email" size=18 maxlength=50></p>
<p style="margin-left:1cm">Password<a style="margin-left:25px"></a> : <input type="password" name="pass" size=18 maxlength=50></p>
<p style="margin-left:1cm">Confirm<a style="margin-left:30px"></a> : <input type="password" name="c_pass" size=18 maxlength=50></p>
<p style="margin-left:1cm">Phone<a style="margin-left:45px"></a> : <input type="text" name="phone" size=18 maxlength=50></p>
<p style="margin-left:1cm">Address<a style="margin-left:30px"></a> : <textarea name="address" max=200></textarea></p>
<p style="margin-left:1cm">EIN<a style="margin-left:50px"></a>   : <textarea name="ein" max=200></textarea></p>
<center><input type="submit" name="edit" value="Edit" /> </center>
</form>
<?php
include "config.php";
if(isset($_REQUEST['edit']))
{
echo "hai";
echo $pass=$_REQUEST['Pass'];
echo $c_pass=$REQUEST['c_pass'];
echo $address=$_REQUEST['address'];
echo $p_name=$_REQUEST['p_name'];
echo $phone=$_REQUEST['phone'];
echo $email=$_REQUEST['email'];
echo $ein=$_REQUEST['ein'];
echo $datz=date('m-d-yy h:i:s');
if($pass==$c_pass)
{
echo $c_pass;
echo $pass;
if($p_name!='' && $address!='' && $p_name!='' && $phone!='' && $email!='' && $ein!='' && $pass!='')
{
echo $sql="insert into register(name,address,contact_name,phone,email,password,ein,c_date) values ('$name','$address','$p_name','$phone','$email','$pass','$ein','$datz')";
if(mysql_query($sql))
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('registered successfully');
</SCRIPT>");
}
else
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('try again');
</SCRIPT>");
}
}
}
}
?>
First of all why do you use the $_REQUEST variable?
It would be much safer if you use $_POST instead.
Can you update your question with your HTML form so we can see what you did there?
Another suggestions is to use mysqli functions or even prepared statements.
With prepared statements you are better protected against SQL injections like Jack mentioned.
If you dont use prepared statements it is really important that you escape the user input before you save it in your Database:
$name = mysqli_real_escape_string($dblink, $name);
And you should not save the passwords in plaintext, at least use MD5.
$pass = md5($pass);
Better use SHA1 as mentioned by BlackPearl:
$pass = sha1($pass);
UPDATE:
I see a typo in your HTML:
<input type="password" name="pass" size=18 maxlength=50></p>
But in your PHP Code you use:
$_REQUEST['Pass']
which is wrong.
you have to use the same name it is case sensitive.
This is a part of my registration form. I want to display back the input user inserted if they forgot to enter all the info needed. However, I get this on my textbox in register form where everyone including my user can see it.
Notice:Undefined variable: name in D:\XAMPP\htdocs\registration.php on line 113
I want it to echo back the input that user had inserted and display it again so that user does not have to enter the same input over again. Help ?
$myusername=($_POST['username']);
$name=($_POST['name']);
if(isset($_POST['username'])) {
echo $_POST['username'];
}
if(isset($_POST['name'])) {
echo $_POST['name'];
}
<input type="text" name="username" size="60" value="<?php echo $myusername; ?>"/>
<input type="text" name="name" size="60" value="<?php echo $name; ?>"/>
Assuming you send the user back to the page they were at previously if the form fails to validate, the POST array is emptied. POST will only carry the information to the page that the form is submitting to.
You can use sessions to save the data in an array, indexed by form field name. Then when the user is sent back to the form, if there are any entries in the array, you can iterate over them through to your form fields.
you can controll the variables with if clause; means you can write:
if ( isset($_POST['send']) && isset($myusername) ) {
echo $myusername;
}
else {
echo '<span style="color:red;">Please complete this field</span>';
}
and do the same in html value for textfiels...
$myusername = isset($_POST['username']) ? ($_POST['username']) : '';
$name = isset($_POST['name']) ? ($_POST['name']) : '';
<input type="text" name="username" size="60" value="<?php echo $myusername; ?>"/>
<input type="text" name="name" size="60" value="<?php echo $name; ?>"/>
Try this, this should remove your error?
if(isset($_POST['username'])) {
$myusername=($_POST['username']);
<input type="text" name="username" size="60" value="<?php echo $myusername; ?>"/>
echo $_POST['username'];
}
if(isset($_POST['name'])) {
$name=($_POST['name']);
<input type="text" name="name" size="60" value="<?php echo $name; ?>"/>
echo $_POST['name'];
}
Here we are checking for POST value first then we using it.
Write the isset function inside the value of each of your .
Exemple :
<input type="text" name="username" size="60" value="
<?php if( isset( $_POST["myusername"] ) )
echo $_POST["myusername"] ?> "/>
you can use this tutorial for validation of input fields in php
http://www.w3schools.com/php/php_form_validation.asp
or you can use this method
<?php
$myusername="";
$name="";
if(isset($_POST['submit'])){
$myusername = $_POST['username'];
$name = $_POST['name'];
}
?>
<form method="POST" action="">
<input type="text" name="username" size="60" value="<?php echo $myusername; ?>"/>
<input type="text" name="name" size="60" value="<?php echo $name; ?>"/>
<input type="submit" name="submit" size="60" value="submit"/>
</form>
I'm trying to create a PHP script to connect an HTML form to a MySQL database, and everything is working except there is one input that cannot be null, and no matter what I do, the system doesn't seem to recognize when I enter text into the field, and I have no idea what I'm doing wrong.
Here's my PHP code:
if (empty($_POST['book_name']))
{$errors[ ] = 'You forgot to enter the book name.';
}
else {
$booktitle = trim($_POST['book_name']);
}
if (empty($_POST['author']))
{$errors[ ] = 'You forgot to enter the author.';
}
else {
$author = trim($_POST['author']);
}
if (empty($_POST['cover']))
{$errors[ ] = 'You forgot to enter the book cover image.';
}
else {
$cover = trim($_POST['cover']);
}
if (empty($_POST['publisher']))
{$errors[ ] = 'You forgot to enter the publisher.';
}
else {
$publisher = trim($_POST['publisher']);
}
if (empty($_POST['language_id']))
{$errors[ ] = 'You forgot to enter the book language.';
}
else {
$languageid = trim($_POST['language_id']);
}
if (empty($_POST['length_pages']))
{$errors[ ] = 'You forgot to enter the book length in pages.';
}
else {
$lengthpages = trim($_POST['length_pages']);
}
if (empty($_POST['fiction']))
{$errors[ ] = 'You forgot to enter if the book is fiction or not.';
}
else {
$fiction = trim($_POST['fiction']);
}
if (empty($_POST['pub_year']))
{$errors[ ] = 'You forgot to enter the year the book was published.';}
else {
$pubyear = trim($_POST['pub_year']);
}
if (empty($errors)) {
require ('mysqli_connect.php');
}
$q = "INSERT INTO books(book_name, author, publisher, language_id, length_pages, cover, fiction, pub_year) VALUES
('$booktitle', '$author', '$publisher', '$languageid', '$lengthpages', '$cover', '$fiction', '$pubyear')";
$r = #mysqli_query($dbc, $q);
if ($r) {
echo 'Thank you! This book information has been entered into the database.';
}
else {
echo 'System error.';
echo mysqli_error($dbc) . ' Query: ' . $q;
foreach ($errors as $msg) {
echo " - $msg<br>\n";
}
}
?>
and here's my HTML code:
<form action="register.php" method="post">
<p>Book name: <input type="text" name="book_name" size="20" maxlength="100" value="<?php if (isset($_POST['book_name'])) echo $_POST['book_name']; ?>" /></p>
<p>Author: <input type="text" name="author" size="20" maxlength="100" value="<?php if (isset($_POST['author'])) echo $_POST['author']; ?>" /></p>
<p>Publisher: <input type="text" name="publisher" size="20" maxlength="100" value="<?php if (isset($_POST['publisher'])) echo $_POST['publisher']; ?>" /></p>
<p>Language:</p>
<p>English <input type="radio" name="language_id" value="1" /></p>
<p>Spanish <input type="radio" name="language_id" value="2" /></p>
<p>French <input type="radio" name="language_id" value="3" /></p>
<p>Italian <input type="radio" name="language_id" value="4" /></p>
<p>Mandarin <input type="radio" name="language_id" value="5" /></p>
<p>Number of pages: <input type="text" name="length_pages" size="20" maxlength="100" value="<?php if (isset($_POST['length_pages'])) echo $_POST['length_pages']; ?>" /></p>
<p>Cover image file name: <input type="text" name="cover" size="20" maxlength="100" value="<?php if (isset($_POST['cover'])) echo $_POST['cover']; ?>" /></p>
<p>Is this book fiction?:</p>
<p>Yes <input type="radio" name="fiction" value="yes" /></p>
<p>No <input type="radio" name="fiction" value="no" /></p>
<p>Year Published: <input type="text" name="pub_year" size="20" maxlength="100" value="<?php if (isset($_POST['pub_year'])) echo $_POST['pub_year']; ?>" /></p>
<input type="submit" name="submit" value="submit" /></form>
And for whatever reason, every time I try to test it out, I get this error message:
"System error. Query: INSERT INTO books(book_name, author, publisher, language_id, length_pages, cover, fiction, pub_year) VALUES ('', 'Not Hayley Munguia', 'Random House', '2', '134', 'howtobenormal.jpg', 'no', '1938') - You forgot to enter the book name."
even though I'm definitely inputting something into the book name field.
I really have no idea what I'm doing wrong, all help is appreciated! Thank you!
First check taking the sentences the mysql and put directly in the phpmyadmin and see the errors. Second I can see is likely the var book_name is empty