I'm attempting to create a form where the user can update their profile details but it just doesn't seem to work.
I'm quite the beginner in server side programming so I'm piecing together code from different tutorials viz. from http://www.codingcage.com/2015/04/php-login-and-registration-script-with.html
The class.user.php file, which originally only had the code for login, and signup. I copied the signup function and changed some stuff to update instead:
public function update($id,$uname,$umob,$uaddr,$uacc,$upass) {
try {
$upass = password_hash($upass, PASSWORD_DEFAULT);
$stmt = $this->conn->prepare(
"UPDATE users
SET
id = :id,
name = :uname,
mobile = :umob,
address = :uaddr,
accNo = :uacc,
password = :upass
WHERE id = :id"
);
$stmt->bindParam(":id", $id);
$stmt->bindParam(":upass", $upass);
$stmt->bindParam(":uacc", $uacc);
$stmt->bindParam(":uname", $uname);
$stmt->bindParam(":uaddr", $uaddr);
$stmt->bindParam(":umob", $umob);
$stmt->execute();
return $stmt;
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
and in view_account.php: (edit 3, whole file including code corrections by #e_i_pi):
<?php
ini_set("error_log", "/path/to/error.log");
require_once("session.php");
require_once("class.user.php");
$auth_user = new USER();
$stmt = $auth_user->runQuery("SELECT * FROM users WHERE consumer-no=:cno");
$userRow = $stmt->fetch(PDO::FETCH_ASSOC);
if(!$session->is_loggedin()){
// session no set redirects to login page
$session->redirect('index.php');
}
if(isset($_POST['submit']) && $_POST['submit'] === 'save') {
$uname = strip_tags($_POST['full-name']);
$umob = strip_tags($_POST['mobile']);
$uaddr = strip_tags($_POST['addr']);
$uacc = strip_tags($_POST['bank-acc']);
$id = strip_tags($_POST['id']);
$upass = strip_tags($_POST['password']);
if($uname=="") {
$signuperror[] = "Please Enter Your Full Name!";
}
else if($umob=="") {
$signuperror[] = "Please Enter Your Mobile No.!";
}
else if($uaddr=="") {
$signuperror[] = 'Please Enter Your Address!';
}
else if($upass=="") {
$signuperror[] = "Please Enter a Password!";
}
else if(strlen($upass) < 6) {
$signuperror[] = "Password must be atleast 6 characters";
}
else {
try {
// I commented out these for some weird reason I can't even rememebr
// $stmt = $auth_user->runQuery("SELECT id FROM users WHERE id=:id");
// $stmt->execute(array(':id'=>$id));
// $row = $stmt->fetch(PDO::FETCH_ASSOC);
$auth_user->update($id,$uname,$umob,$uaddr,$uacc,$upass);
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Gas Booking</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<h1>gas booking</h1>
<nav>
<ul>
<li>home</li>
<li>booking</li>
<li>payment</li>
<li>ticket</li>
<li>view account</li>
<li>bank</li>
<li>logout</li>
</ul>
</nav>
</header>
<div class="content">
<h2>Edit Your Profile Details</h2>
<form method="post" action="view_account.php">
<input type="hidden" id="id" name="id" value="<?php echo $_SESSION['id']; ?>">
<label for="full-name" class="input-info">
<div class="label">full name</div>
<input type="text" id="full-name" name="full-name" value="<?php echo $_SESSION['name']; ?>">
</label>
<label for="mobile" class="input-info">
<div class="label">mobile number</div>
<input type="text" id="mobile" name="mobile" value="<?php echo $_SESSION['mob']; ?>">
</label>
<label for="addr" class="input-info">
<div class="label">address</div>
<input id="addr" name="addr" value="<?php echo $_SESSION['addr']; ?>">
</label>
<label for="bank-acc" class="input-info">
<div class="label">bank account number</div>
<input type="text" id="bank-acc" name="bank-acc" value="<?php echo $_SESSION['accNo']; ?>">
</label>
<hr>
<label for="password" class="input-info">
<div class="label">password</div>
<input type="password" id="password" name="password">
</label>
<button type="submit" name="submit" value="save">
Save Changes
</button>
</form>
</div>
</body>
</html>
and my table is as follows:
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`consumerNo` varchar(15) NOT NULL,
`password` varchar(255) NOT NULL,
`accNo` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
`mobile` bigint(10) NOT NULL,
`balance` bigint(10) NOT NULL,
`joining_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
I'm sure I've done something stupid. I'd really appreciate pointing me in the right direction, I sat with it till 5:00am and am feeling frustrated with myself.
The connection with the db is working, classes are properly included. Let me know if you need more information. Thank you!
The project can be downloaded here: https://www.dropbox.com/s/9v69m18l82n1t46/gas.zip?dl=0. Warning the code's kind of a mess.
Update
You seem to be doing the following in view-account.php:
try {
$auth_user->update($id,$uname,$umob,$uaddr,$uacc,$upass);
} catch(PDOException $e) {
echo $e->getMessage();
}
Yet you're already try/catch'ing within your update() method. I assume it never gets to this as an error in your if/elseif/elseif/else/etc checks is picked up. Could you modify it to look like this for testing purposes:
$errors = [];
if ($uname == "") {
$errors[] = "Please Enter Your Full Name!";
}
if ($umob == "") {
$errors[] = "Please Enter Your Mobile No.!";
}
if ($uaddr == "") {
$errors[] = 'Please Enter Your Address!';
}
if ($upass == "") {
$errors[] = "Please Enter a Password!";
}
if (strlen($upass) < 6) {
$errors[] = "Password must be atleast 6 characters";
}
// check errors
if (!empty($errors)) {
print_r($errors);
return false;
}
// otherwise try the query:
$obj = $auth_user->update($id, $uname, $umob, $uaddr, $uacc, $upass);
and let us know what comes up!
I assume you'd have an error thrown, something along the lines of;
SQLSTATE[HY093]: Invalid parameter number
This is because you're trying to bind on :id twice. You have to remember that a users ID is unique and should never change (right?).
Modify your query to look like this:
$stmt = $this->conn->prepare(
"UPDATE users
SET
name = :uname,
mobile = :umob,
address = :uaddr,
accNo = :uacc,
password = :upass
WHERE id = :id"
);
Notes
You're best to modify your "password change" functionality to have the user confirm their password (if(PASSWORD == PASSWORD_REPEAT) { .... SET PASSWORD...)
Don't pass the user ID inside the form. It's insecure. Since it's in $_SESSION already, simply access it like that within your view-account.php file!
Why the above you ask? Simple. If I inspect your <form... element, I could easily modify that hidden input to be some other users ID, allowing me to change their passwords/information/etc.
And since it looks like you're dealing with "Bank" related information, I'd suggest doing this asap! Imagine If I could change "Barack Obama's" bank password and access his account.
Your form also doesn't have any action attribute...so it does nothing.. Best change that to your view-account.php page
I suggest removing your use of strip_tags(). It could ruin some fields (i.e. passwords). You're also already binding/preparing your statements (Props to you on that, good work!)
While we're at it, you might want to look at your view-account.php file, It could be modified to stop the use of all those if / elseif / elseif / else statements. You're essentially checking all your fields and if it fails, you're adding an error message to an array, but if it passes you're running the query, this is bad practice. You should look at doing something similar to (pseudo code):
$errors = [];
if (!check_fields()) {
$errors[] = THE FIELD ERROR MESSAGE;
}
// now check if your errors are empty or not
if(!empty($errors)) {
// this means we have errors in the form.
// return the errors array to the front end and handle it appropriately.
return $errors;
}
// otherwise we can try the query here now!
try {
// YOUR SQL UPDATE QUERY
} .....`
Righto, you have a few problems with things not matching up etc., which is to be expected if you are starting out.
Let's start with the HTML form. There are two issues here:
The form has no action property, so it doesn't get submitted anywhere
The submit button is given a specific name and no value. (While some will consider this okay, maybe we can try a different approach which is a little more sensible)
I would suggest your HTML form be changed to this:
<form method="post" action="view-account.php">
<input type="hidden" id="id" name="id" value="<?php echo $_SESSION['id']; ?>">
<label for="full-name" class="input-info">
<div class="label">full name</div>
<input type="text" id="full-name" name="full-name" value="<?php echo $_SESSION['name']; ?>">
</label>
<label for="mobile" class="input-info">
<div class="label">mobile number</div>
<input type="text" id="mobile" name="mobile" value="<?php echo $_SESSION['mob']; ?>">
</label>
<label for="addr" class="input-info">
<div class="label">address</div>
<input id="addr" name="addr" value="<?php echo $_SESSION['addr']; ?>">
</label>
<label for="bank-acc" class="input-info">
<div class="label">bank account number</div>
<input type="text" id="bank-acc" name="bank-acc" value="<?php echo $_SESSION['accNo']; ?>">
</label>
<hr>
<label for="password" class="input-info">
<div class="label">password</div>
<input type="password" id="password" name="password">
</label>
<button type="submit" name="submit" value="save">
Save Changes
</button>
</form>
Now, once this form is submitted to view-account.php, we want to make sure that the submit button is "save" mode, so we change the first line of view-account.php to this:
if(isset($_POST['submit']) && $_POST['submit'] === 'save') {
This approach means we can have different submit buttons on the same form - we may in future want actions for save, delete, archive, etc.
Lastly, I notice that the id field in your database table is declared AUTOINCREMENT. Great, exactly what you want, database id fields are internal unique identifiers that we let the database determine (in 99% of cases - there are edge cases where we like to define our own UIDs). This means that there is a problem with your UPDATE statement. You cannot update an auto-incremented field. In your class.user.php file, change the declaration of $stmt to this:
$stmt = $this->conn->prepare(
"UPDATE users
SET
name = :uname,
mobile = :umob,
address = :uaddr,
accNo = :uacc,
password = :upass
WHERE id = :id"
);
This should fix your code issues, I think I got everything. BUT, there may be other problems. If your code still does not work, I would suggest checking your error logs. If you're not sure where they are, either check your php.ini file to see what the error log location is, or override the default location by putting this at the top of the page you're trying to debug:
ini_set("error_log", "/path/to/error.log");
Related
I working on two pages, a first one which has a form with three fields: name, email and message). This page will send these data to a second page, that will validate if those fields meet the criteria.
If on the second page, any of those fields does not meet the criteria, I want to redirect to the first page (or a third php one), fill the form with previous information and tell the user to correct the fields properly.
I'm strugling to send the data form the second page to the first (or third) one. Does anyone knows a good way to do it?
Here's my code:
First page - contato.html
<form action="validate.php" method="POST" name="emailform">
<div class="form-group">
<input type="text" id="name" name="nome" placeholder="Type your name">
</div>
<div class="form-group">
<input type="text" id="email" name="email" placeholder="type your#email.com here">
</div>
<div class="form-group">
<textarea class="form-control" cols="30" rows="10" maxlength="300" id="message" name="mensagem" placeholder="Leave your message." ></textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" value="Send message" onclick="alert('Thank you!')" ></form>
Second Page - validate.php
if(isset($_POST['nome'])) $nome = $_POST['nome'];
if(isset($_POST['email'])) $email_visitante = $_POST['email'];
if(isset($_POST['mensagem'])) $mensagem = $_POST['mensagem'];
// if does not meet the criteria, redirect to contato.html and update the form with the info
if(empty($nome)){
Header("location:contato.html");
}
if(empty($email_visitante)){
Header("location:contato.html");
}
if(empty($mensagem)){
Header("location:contato.html");
}
// check for letters and space only
if (!preg_match("/^[a-zA-Z ]*$/",$nome)) {
Header("location:contato.html");
}
// check if e-mail address is well-formed
if (!filter_var($email_visitante, FILTER_VALIDATE_EMAIL)) {
Header("location:contato.php");
}
Does anyone knows how to do it? Either sending to a third page or redirecting to the first one (and fill the form in again)
You have to use sessions and store data there in one page and access in another, here is a small usage
<?php
// page 1
session_start();
// Set session variables
$_SESSION["nome"] = $nome;
$_SESSION["email"] = $email_visitante;
$_SESSION["mensagem"] = $mensagem;
<?php
// page 2|3|N - any other page
session_start();
// Get session variables
$nome = $_SESSION["nome"];
$email_visitante = $_SESSION["email"];
$mensagem = $_SESSION["mensagem"];
Part of your problem is that upon any failed validation you are using a redirect. Alternatively you can display an error message to the user: suggesting they need to correct their input by going back a page (browser back).
When forms get longer users need some hand holding with error correction. Their errors need to be clearly indicated with a message alongside as to how they can fix it.
Avoiding using the 'browser back' method above it's common to have the form send to its own url. I've included an example below.
By doing this you can repopulate the form with posted values upon error and add error feedback. You must be careful to escape user input in this situation.
I've added a generic error feedback notice. Which isn't that helpful in its current form. You could improve upon this by adjusting the validation code to return an array of error notices and use that within your form for more targeted error feedback. You could also add - all fields are required - text to help the user.
Upon successful validation that's when to redirect the user to a confirmation page. This can prevent form resubmissions.
Your name regex pattern in its current form will not allow hyphens or apostrophes. I haven't changed it below. Do bear this in mind. "Michael O'leary" would be faced with an error and likely not understand why. You need to be careful when using strict rules for user input. Also this will reject some unicode.
You also need to escape user input appropriately. Note that you may be satisfied that the name and email after validation follows a particular pattern, but becareful of raw user input. The message text is passed on raw after validation.
<?php
$nome = $_POST['nome'] ?? null;
$email_visitante = $_POST['email'] ?? null;
$mensagem = $_POST['mensagem'] ?? null;
$feedback = null;
if(isset($_POST['submit'])) {
if(validate($nome, $email_visitante, $mensagem) !== false) {
process($nome, $email_visitante, $mensagem);
// Redirect to success/thankyou/confirmation page.
header('location:success.html');
exit;
}
// This is a generic message, could this be more helpful?
$feedback = 'Your form has errors. Please correct them.';
}
form($nome, $email_visitante, $mensagem, $feedback);
function process($nome, $email_visitante, $mensagem) {
// do something with your values.
}
function validate($nome, $email_visitante, $mensagem) {
if(empty($nome)) {
return false;
}
if(empty($email_visitante)){
return false;
}
if(empty($mensagem)){
return false;
}
if (!preg_match("/^[a-zA-Z ]*$/",$nome)) {
return false;
}
if (!filter_var($email_visitante, FILTER_VALIDATE_EMAIL)) {
return false;
}
return true;
}
function form($nome = null, $email_visitante = null, $mensagem = null, $feedback = null) {
?>
<?= $feedback ?>
<form action='' method='POST' name='emailform'>
<div class='form-group'>
<label for='name'>Your name:</label>
<input type='text' id='name' name='nome' value='<?= htmlspecialchars($nome) ?>'>
</div>
<div class='form-group'>
<label for='email'>Your email address:</label>
<input type='text' id='email' name='email' value='<?= htmlspecialchars($email_visitante) ?>'>
</div>
<div class='form-group'>
<label for='message'>Your message:</label>
<textarea class='form-control' cols='30' rows='10' maxlength='300' id='message' name='mensagem'><?= htmlspecialchars($mensagem) ?></textarea>
</div>
<div class='form-group'>
<input type='submit' name='submit' value='Send message'>
</div>
</form>
<?php
}
I'm trying to validate the user input and query to delete the record which have the same name. I'm using phpStorm for coding
I have tried to go over the typo, format of the code and check the query in phpAdmin and it's working fine
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 3/24/2019
* Time: 4:38 PM
*/
// Include config file
require_once "config.php";
$product_name= '';
$product_name_err = '';
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST")
{
if(empty(trim($_POST["product_name"]))){
$product_name_err = "Please enter the product name.";
} else{
$product_name = trim($_POST["product_name"]);
}
//Delete the data in the product table
$sql = "DELETE FROM `products` WHERE `name` = '$product_name'";
if ($product_name_err =''){
mysqli_query($link,$sql);
}
}
?>
<?php include "header_admin.php"?>
<div class="wrapper">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group" <?php echo (!empty($product_name_err)) ? 'has-error' : ''; ?>>
<label>Product name</label>
<input type="text" name="product_name" class="form-control" >
<span class="help-block"><?php echo $product_name_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Delete Item">
</div>
</form>
</div>
<?php include "footer.php"?>
I expect the preceding code to check if the field is blank and the query delete that matched record on the database but either of them seem to work properly. The $product_name seem not received any value at all.
The below code should work correctly. There was a typo in your confition: if ($product_name_err =''){ should be if ($product_name_err ==''){
Also, your code was vunerable to injection attacks, which is fixed below by using the mysqli_escape_string function.
if($_SERVER["REQUEST_METHOD"] == "POST") {
$product_name = mysqli_escape_string($link, trim($_POST["product_name"]));
if(empty($input)){
$product_name_err = "Please enter the product name.";
}
//Delete the data in the product table
$sql = "DELETE FROM `products` WHERE `name` = '$product_name'";
if($product_name_err == ''){
mysqli_query($link,$sql);
}
}
Your if condition is incorrect, use '==' instead of '='.
if ($product_name_err ==''){
mysqli_query($link,$sql);
}
also you should really consider using prepared statements to prevent sql injection attacks and it does other nice things for you like you not having to escape ' or " characters from your strings.
More info on prepared statements
Php code check will help to check your PHP code. May be it will help you.
#PHP Code Checker
An advanced, custom PHP code checker that searches your code for common, hard to find typos and mistakes; includes a syntax check.
Whenever I try to login with incorrect information I don't get the error message, It just resets my form when I try to login with incorrect information. I think I might have a conflicting code somewhere. Is there something wrong with my code? Or if possible is there any other way to provide validation based on my code?
Everything works fine. I just need the validation.
My PHP:
<?php
session_start();
ob_start();
//Include the database connection file
include "database_connection.php";
//Check to see if the submit button has been clicked to process data
if(isset($_POST["submitted"]) && $_POST["submitted"] == "yes")
{
//Variables Assignment
$username = trim(strip_tags($_POST['username']));
$user_password = trim(strip_tags($_POST['passwd']));
$validate_user_information = mysql_query("select * from `signup_and_login_users_table` where `username` = '".mysql_real_escape_string($username)."' and `password` = '".mysql_real_escape_string($user_password)."'");
//Validate against empty fields
if($username == "" || $user_password == "")
{
$error = '<br><div class="info">Sorry, all fields are required to log into your account. Thanks.</div><br>';
}
elseif(mysql_num_rows($validate_user_information) == 1) //Check if the information of the user are valid or not
{
//The submitted info of the user are valid therefore, grant the user access to the system by creating a valid session for this user and redirect this user to the welcome page
$get_user_information = mysql_fetch_array($validate_user_information);
$_SESSION["VALID_USER_ID"] = $username;
$_SESSION["USER_FULLNAME"] = strip_tags($get_user_information["fullname"]);
header("location: home.php");
}
else
{
//The submitted info the user are invalid therefore, display an error message on the screen to the user
$error = '<br><div class="info">Sorry, you have provided incorrect information. Please enter correct user information to proceed. Thanks.</div><br>';
}
}
?>
My form:
<div class="login">
<font color="black" size="5"><p>Employee Login</p></font>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="username" placeholder="Username" required="required" />
<input type="password" name="passwd" placeholder="Password" required="required" />
<input type="hidden" name="submitted" id="submitted" value="yes">
<button type="submit" name="submit" class="btn btn-primary btn-block btn-large">Login</button>
<p></p>
<a href="index.php"><img src="img/homebutton.png" height="35px" width="35px">
</form>
</div>
First of all use mysqli functions not mysql because they are now deprecated.
Secondly, the reason you are not getting the error message is because you have not printed the error message. You should add echo $error; after you defined your error variable
This is an effort to create a PHP page to add data to a table. I am getting a parsing error on line 79 so I have been fiddling with it for a while:
Parse error: syntax error, unexpected T_STRING in /home/sharah19/dev.rahmaninet.org/new.php on line 79
Also I have another question: Whats the easiest way to make this page secure? So only users who are authenticated through the login page can add a record?
The contents of new.php:
<?php
/*
NEW.PHP
Allows user to create a new entry in the database
*/
// 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($first, $last,$email, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Add a New Record</title>
<link href="rahmani.css" rel="stylesheet">
</head>
<body>
<div id="main">
<h1>RahmaniNET CRM System</h1>
<?php include("header.php"); ?>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<div>
<strong>First Name: *</strong> <input type="text" name="first_name" value="<?php echo $first_name; ?>" /><br/>
<strong>Last Name: *</strong> <input type="text" name="last_name" value="<?php echo $last_name; ?>" /><br/>
<strong>email: *</strong> <input type="text" name="email" value="<?php echo $email; ?>" /><br/>
<p>* required</p>
<input type="submit" name="submit" value="Submit">
</div>
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.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
$first_name = mysql_real_escape_string(htmlspecialchars($_POST['first_name']));
$last_name = mysql_real_escape_string(htmlspecialchars($_POST['last_name']));
$email = mysql_real_escape_string(htmlspecialchars($_POST['email']));
// check to make sure both fields are entered
if ($first_name == '' || $last_name == ''|| $email == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($first_name, $last_name, $email, $error);
}
else
{
// save the data to the database
mysql_query("INSERT contacts SET first_name='$first_name', last_name='$last_name',email ='$email' )
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('$first', '$last','$email', $error);
}
?>
The error comes from the lack of a closing quote on your MySQL query:
mysql_query("INSERT contacts SET first_name='$first_name', last_name='$last_name',email ='$email') or die(mysql_error());
It should be:
mysql_query("INSERT contacts SET first_name='$first_name', last_name='$last_name',email ='$email'") or die(mysql_error());
Also you ask:
Also I have another question: Whats the easiest way to make this page
secure? So only users who are authenticated through the login page can
add a record?
If you are using Apache then you should you use Apache AuthType Basic. More details are here. Details under “Getting it working.”
You are missing a double quote in your sql string:
mysql_query("INSERT contacts SET first_name='$first_name', last_name='$last_name',email ='$email' )
i have this php code in my form. I used pdo to get into mysql database and insert data. A simple form where use enters his name, email, comments, and a checkbox. I use this in jquery mobile environment.
<?php
$hostname = 'localhost';
$username = 'root';
$password = '';
$dbName = 'database';
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=$dbName", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->exec('SET NAMES "utf8"');
}
catch(PDOException $e)
{
echo "Sorry, you are experiencing server Error: ".$e->getMessage();
exit();
}
if(isset($_POST['sendEmail']))
{
try
{
$senderName = $_POST['sendName'];
$senderEmail = $_POST['sendEmail'];
$comments = $_POST['comments'];
if (isset($_POST['offer'])) {
$offer = 1;
} else {
$offer = 0;
}
$dateTimeSent = date('Y-m-d H:i:s');
$q= "INSERT INTO comments(sendName, sendEmail, comments, offer, dateTimeSent) VALUES (:sendName, :sendEmail, :comments, :offer, :dateTimeSent);";
$query = $dbh ->prepare($q);
$results = $query->execute(array(
":senderName"=>$sendName,
":senderEmail"=>$sendEmail,
":comments"=>$comments,
":dateTimeSent"=>$dateTimeSent,
":offer"=>$offer,
));
}
catch (PDOException $e)
{
$error = 'Error adding elements to database: ' . $e->getMessage();
include 'error.html.php';
exit();
}
exit();
}
?>
This is the form I use:
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST" name="comments" id="comments">
<div data-role="fieldcontain">
<label for="sendName">From: </label>
<input type="text" name="sendName" class="validate[required"] id="sendName" data-clear-btn="true" placeholder="Enter name" required >
</div>
<div data-role="fieldcontain">
<label for="sendEmail">Email: </label>
<input type="email" name="sendEmail" id="sendEmail" class="validate[required,custom[email]]" data-clear-btn="true" placeholder="valid_email#true.com" required >
</div>
<label for="comments"></label>
<textarea name="comments" id="comments" value="comments"></textarea>
<label for="offer">
<label for="offer">
<input name="offer" type="checkbox" id="offercheckbox">Please check</label>
</label>
<input type="button" name="Send Email" value="Submit" id="suggestSubmit" onclick="submitForm()">
</form>
My problem is I am trying to figure out how to clear the form fields after a successful submission. I found an option of using Jquery onclick function. I inserted this code before the end of form tag:
<script>
function submitForm() {
$('form[name="comments"]').submit();
$('input[type="email"], textarea').val('');
$('input[type="text"], textarea').val('');
}
</script>
However, if the form was submitted but failed in the jquery validation, all the fields will been cleared even if the submission failed due to but not limited to form validation. So the user when fixing his errors has to reenter all data in all the form fields again. Not good.
I checked the other answers here and other online sources, but i cant seem to make it work.
What`s is the best approach in clearing form fields after a successful submission, if I use PHP-PDO in jquery mobile?
PS. I am a newbie. Thanks.
After a successful submission do http redirect to the form page using header function, this is a pretty new request which should view forms elements in the page with empty status, just like the user is visiting this page for the first time.
It would also be nice to view a success message for the user when opening this page in order to get the sense that his previous request has been processed successfully.