Log in

View Full Version : Keeping the form from submitting after validation



?foru
02-27-2009, 02:04 AM
I have an in-depth anti-spam/profanity/exploits script that I will share if anyone would like it. The current project just needs some basic validation and isn't as extreme as the other so trying to rewrite it would be too involved.

This form will show the info/update all in the same page.

PHP code to pull id and info from database is here above the form and is closed with a ?> tag...

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type=hidden name="id" value="<?php echo $myrow["id"] ?>">

TN:<br><input type="text" name="tn" value="<?php echo $myrow["tn"] ?>" size=30><br><br>
Account Number:<br><input type="text" name="acct_number" value="<? echo $myrow["acct_number"] ?>"size=30><br><br>
Port:<br><input type="text" name="port" value="<? echo $myrow["port"] ?>" size=3><br><br>
FQDN:<br><input type="text" name="fqdn" value="<?php echo $myrow["fqdn"] ?>" size=35> <a href="<?php echo $_SERVER['PHP_SELF']; ?>?cmd=delete&id=<?php echo $myrow["id"] ?>" onclick="javascript:return confirm('Are you sure you want to delete this item ? It cannot be undone')">delete this item from the database</a><br />
<input type="hidden" name="cmd" value="edit">
<input type="submit" name="submit" value="submit">
</form>

<? } ?>
<?
if ($_POST["$submit"])
{
// START VALIDATION
if ( empty($_POST['fqdn']) )
echo 'fqdn is required';
// END VALIDATION

$tn = $_POST["tn"];
$acct_number = $_POST["acct_number"];
$port = $_POST["port"];
$fqdn = $_POST["fqdn"];

$sql = "UPDATE toast_data SET tn='$tn', acct_number='$acct_number', port='$port', fqdn='$fqdn' WHERE id=$id";
$result = mysql_query($sql);
echo "<BR><BR><table><tr><td class='confirm'>Thank you! Information updated.</td></tr></table>";
echo "<BR><BR>";
echo "<a href='". $_SERVER['PHP_SELF']. "'>Update another record</a>";
}
}
?>

Since the code will continue to execute I need to stop it to display the form again until all fields are filled in. I might be thinking wrong here but I had an idea of running a function after the echo statement like showform(); and I've used exit before to terminate any further script execution. showform(); would maybe take you back to the beginning of the form if I'm thinking correctly. For now I don't need any type of expression checking just basic empty fields check because users will mainly be copy/pasting from information already in front of them.

Something like this would also simplify things since users know that all fields are required but might mistakenly have one empty.

empty($_POST['tn']) || empty($_POST['acct_number']) || empty($_POST['port']) || empty($_POST['fqdn']))
echo 'All fields are required';

My thinking might be off and someone may know a much easier way of doing this, but I would appreciate any assistance.

JasonDFR
02-27-2009, 07:15 AM
Generally, all the form processing is done at the top of the script. This allows you to echo out the variables that the user entered in case there were any errors.

As far as your database query not exectuing if there is an error, you need to put it inside a conditional. If ( no errors ) query else don't query.

I did the code below in this thread http://www.dynamicdrive.com/forums/showthread.php?t=42251



<?php

if (isset($_POST['submit'])) {

$e = array(); // An empty array to hold possible error messages

// Your validation is going to be different, but you can use this for a guide
// Everytime an error occurs, add an error message to the errors array.

if (!ereg("^[a-zA-Z]+$", $firstName) ) {
$e[] = 'Please enter a valid Name<br>';
}

if (!ereg("^[a-zA-Z]+$", $lastName) ) {
$e[] = 'Please enter a valid Last name<br>';
}

if ( !(isValidEmail($email)) ) {
$e[] = 'Please enter a valid Email<br>';
}

if ( $countryOfResidence=='' ) {
$e[] = 'Please select Country of residence<br>';
}

if ( $phoneCountry=='' ) {
$e[] = 'Please select Phone country<br>';
}

if ( !is_numeric($areaCode) ) {
$e[] = 'Please enter valid Area code<br>';
}

if ( !is_numeric($phoneNumber) ) {
$e[] = 'Please enter valid Phone number<br>';
}

if ( empty($e) ) { // If the errors array is empty, there were no errors; this is the key to
// your problem

// Do your database query here

if ( database update is successful ) {

$success = true; // OR send to another page: header('Location: /thankyou.php');

}

}

}
?>

<html>

<head>
<title></title>
</head>

<body>

<?php

// Here you can decide if you want to give any success feedback to the user

if ( isset($success) ) { // If you are not redirecting to a success page.

echo '<p>Thank you.</p>';

} else { // Form either hasn't been submitted or wasn't successful

if ( !empty($e) ) { // If errors array is not empty echo them

foreach ( $e as $msg ) {

echo $msg;

}

}
?>

<!-- YOUR FORM HERE action="<?php echo $_SERVER['PHP_SELF']; ?>" -->

<?php
}
?>

</body>

</html>

Let me know if you have any questions.

?foru
02-28-2009, 12:19 AM
Thank you for the example! The comments helped to piece it all together. I was able to take your example and fit it into what I needed.

I do have one issue though. I noticed that the validation is working just fine on my 4 fields but if just one field is blank and it needs to give the specific error ...the information in all the fields is being cleared. Could that be solved with a SESSION maybe? Thank you

JasonDFR
02-28-2009, 07:08 AM
No, don't use sessions for that.

In the value="" attribute of your form elements put


value="<?php echo $_POST['firstName'] ? $_POST['firstName'] : ''; ?>"

This code checks to see if $_POST['firstName'] exists (is true), then echos it if it is, otherwise '' (nothing) gets echoed.

If you are showing your form after submission is successful, you should clear the $_POST array so the successful values don't continue to show up.

And a note on SESSIONS. Try not to use them unless absolutely necessary. Your pages should remain as stateless as possible. That is to say, once an HTTP request is made, you get the information you need, process it, output it, and then it is gone. Usernames and userids are good things to store in sessions.

Good luck.

?foru
03-01-2009, 12:37 AM
This is working, but after testing it a bit there is one piece I can't quite figure out.

The cmd and id are passed through the URL like ?cmd=edit&id=5

Initially the form was setup with <?php echo $myrow["tn"] ?> for the value...so it takes the info from the database and fills in the form data

So I tacked that one the front like... (which I think is trying to do too much)

value="<?php echo $myrow["tn"] ?><?php echo $_POST['tn'] ? $_POST['tn'] : ''; ?>"

When the form is shown and all the values populate you can make changes and the database updates like it should.

This is the part I can't figure out...
If for some reason you erase a value and an error is given (like it should) the existing form data does stay in those fields correctly but the database doesn't update.

You've been a great help so far and I really appreciate it.

JasonDFR
03-01-2009, 10:45 AM
I think you need to fill in the fields with the current information from the database when the form is first displayed.


if ( empty($e) ) { // If the errors array is empty, there were no errors; this is the key to
// your problem

// Do your database query here

if ( database update is successful ) {

$success = true; // OR send to another page: header('Location: /thankyou.php');

}

}

}

// Query database here to get the initial values for your update form.


?>

<html>

<head>
<title></title>


In the form, get rid of the post values and put the values from the database.


value="<?php echo $myrow['tn']; ?>"

Let me know how that works.

?foru
03-02-2009, 04:20 PM
I had the database fill out the form with just
<?php echo $myrow["tn"] ?>when the id is passed in the URL like page.php?cmd=edit&id=5 and the validation worked properly but the form fields would empty when you submitted the form and there was an error in one of the fields.

The last part of code you provided corrected the form fields from emptying...

<?php echo $_POST['tn'] ? $_POST['tn'] : ''; ?>


Below is the whole page code that fills in the values correctly from the database and updates if you make a change and submit.
When the fields are populated from the database and you remove a value and submit which gives an error(like it should)...when the error is cleared and the form is submitted the database doesn't update which is what I can't figure out.

<?php
$con = mysql_connect("db_host", "db_user","db_pass");
mysql_select_db("db_name");
$result = mysql_query("SELECT * FROM toast_data ORDER BY id");

if($_REQUEST['action']=="del") {
mysql_query("DELETE FROM toast_data WHERE id={$_REQUEST['id']};");
}
?>
<?php

if (isset($_POST['submit'])) {

$e = array(); // An empty array to hold possible error messages

if ( $tn=='' ) {
$e[] = 'Please enter the TN<br>';
}
if ( !is_numeric($tn) ) {
$e[] = 'Please enter a valid phone number<br>';
}
if ( $acct_number=='' ) {
$e[] = 'Please enter the Account Number<br>';
}
if ( !is_numeric($port) ) {
$e[] = 'Please enter the port number<br>';
}
if ( $fqdn=='' ) {
$e[] = 'Please enter the FQDN<br>';
}

if ( empty($e) ) { // If the errors array is empty, there were no errors;


// query database
$tn = $_POST["tn"];
$acct_number = $_POST["acct_number"];
$port = $_POST["port"];
$fqdn = $_POST["fqdn"];

$sql = "UPDATE toast_data SET tn='$tn', acct_number='$acct_number', port='$port', fqdn='$fqdn' WHERE id=$id";
$result = mysql_query($sql);
echo "<BR><BR><table><tr><td class='confirm'>Thank you! Information updated.</td></tr></table>";
echo "<BR><BR>";
echo "<a href='". $_SERVER['PHP_SELF']. "'>Update another record</a>";

if (isset($result)) {

$success = true; // OR send to another page: header('Location: /thankyou.php');

}

}

}
?>

<html>
<head>
<title></title>
</head>

<body>

<?php

// Here you can decide if you want to give any success feedback to the user

if ( isset($success) ) { // If you are not redirecting to a success page.

echo '<p>Thank you.</p>';

} else { // Form either hasn't been submitted or wasn't successful

if ( !empty($e) ) { // If errors array is not empty echo them

foreach ( $e as $msg ) {

echo $msg;

}

}
?>
<? //edit individual items//////////////////////////////////////////
if($_GET["cmd"]=="edit" || $_POST["cmd"]=="edit")
{

if (!isset($_POST["submit"]))
{
$id = $_GET["id"];
$sql = "SELECT * FROM toast_data WHERE id=$id";
$result2 = mysql_query($sql);
$myrow = mysql_fetch_array($result2); }
}
?>
<br />
<form action="<?php echo $_SERVER['PHP_SELF']; ?>?cmd=edit&id=<?php echo $myrow["id"] ?><?php echo $_POST['id'] ? $_POST['id'] : ''; ?>" method="post">
<input type=hidden name="id" value="<?php echo $myrow["id"] ?>">

TN:<br><input type="text" name="tn" value="<?php echo $myrow["tn"] ?><?php echo $_POST['tn'] ? $_POST['tn'] : ''; ?>" size=30><br><br>
Account Number:<br><input type="text" name="acct_number" value="<? echo $myrow["acct_number"] ?><?php echo $_POST['acct_number'] ? $_POST['acct_number'] : ''; ?>"size=30><br><br>
Port:<br><input type="text" name="port" value="<? echo $myrow["port"] ?><?php echo $_POST['port'] ? $_POST['port'] : ''; ?>" size=3><br><br>
FQDN:<br><input type="text" name="fqdn" value="<?php echo $myrow["fqdn"] ?><?php echo $_POST['fqdn'] ? $_POST['fqdn'] : ''; ?>" size=35><br>

<input type="hidden" name="cmd" value="edit">

<input type="submit" name="submit" value="submit">

</form>

<?php
}
?>

</body>
</html>
Thank you

?foru
03-03-2009, 04:13 PM
I found the problem.

I was missing
<?php echo $_POST['id'] ? $_POST['id'] : ''; ?>

in my hidden id field

<input type=hidden name="id" value="<?php echo $myrow["id"] ?><?php echo $_POST['id'] ? $_POST['id'] : ''; ?>">

When the error was being given and the correction was made the id dropped off the URL so it didn't actually know what row to update in the database.

When an error wasn't given the id stayed intact and therefore the database updated.