If I have a form with lots of fields, how can I write code that will check each one to make sure it is entered, and if not, print the error, and if so, run the query? Here's what I have:
if (empty($_POST['field1']) || empty($_POST['field2'])) {
$f1 = FALSE;
$f2 = FALSE;
$message .= '<p>You must complete every part of the form.</p>';
} else {
$f1= escape_data($_POST['field1']);
$f2 = escape_data($_POST['field2']);
}
if ($f1 && $f2) {
$query = "INSERT INTO tablename (field1,field2) VALUES ('$f1', '$f2')";
$result = @mysql_query ($query);
}
This is ok if I only have one or two fields, but if I have 30 or so, all the copy/pasting can get tedious. Is there a function that can find out what all the field names in my form are, set variables to them (I'm not sure if that part is even necessary), make sure they're all filled out, and put them into the table?
Thanks.
PHP/MYQL newbie needs help
Moderator: General Moderators
You could use javascript. This function checks all text & file upload fields in the form & displays a messagebox with the missing fields displayed. put this between your <head></head> tags
Then, put this in the first <form> tag.
Code: Select all
<script type="text/javascript">
<!-- Hide the script from older browsers
function isblank(s)
{
for(var i=0;i<s.length;i++)
{
var c = s.charAt(i);
if((c != ' ')&&(c !='\n')&&(c != '\t')) return false;
}
return true;
}
function verify(f)
{
var msg;
var empty_fields = "";
var errors = "";
for(var i=0;i<f.length;i++)
{
var e = f.elementsїi];
if(((e.type == "text")||(e.type == "file"))&& !e.optional)
{
if((e.value == null)||(e.value == "")|| isblank(e.value))
{
empty_fields += "\n " + e.name;
continue;
}
}
}
if(!empty_fields && !errors) return true;
msg = "______________________________________________________\n\n"
msg += "The update was not submitted because of the following error(s).\n";
msg += "Please correct there error(s) and re-submit.\n";
msg += "______________________________________________________\n\n"
if (empty_fields)
{
msg += "-The following required fields are empty:"
+ empty_fields + "\n";
if(errors) msg += "\n";
}
msg += errors;
alert(msg);
return false;
}
// end hiding -->
</script>Code: Select all
onSubmit="return verify(this)"-
kettle_drum
- DevNet Resident
- Posts: 1150
- Joined: Sun Jul 20, 2003 9:25 pm
- Location: West Yorkshire, England
Or if you still want to have the user submit the form and for php to check it, you could easily make your own function to check that required fields were filled in. Just have it except an array of the field names that are required, then the function just needs to loop through the array and check to see that there is a value in it:
If the function doesnt return anything then you know that all the required fields were filled in. Easy 
Code: Select all
function field_check($required){
foreach($required as $q){
if(empty($_POST[$q])){
return "Error: The following field was not filled in: $q";
}
}
}