Re: Required fields in a form?
| From: | Daniel Convissor | Date: | Mon, 16 Oct 2000 04:58:37 +0000 |
| Subject: | Re: Required fields in a form? | ||
| References: | 1 2 3 4 5 6 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-20298@lists.php.net to get a copy of this message | ||
Erica Douglass wrote:
>
> Agh... still having problems...
>
> Alright. Following Joe's example, I rewrote the code to get the required
> fields from the database. That works fine. My problem is that when a field
> is blank, nothing is written into the value part of the array for that key,
> so I get a PHP warning when trying to submit my form. For reference
> purposes, $f is my form field array. $f works just fine. It just doesn't
> set values for blank fields.
>
> Here is my code:
>
> $query = "select field_name from form_fields where
> required=\"yes\"";
> $result = mysql_query ($query) or die ("The server is down. Here's
> what MySQL said: " . mysql_error());
Here's a few pointers to shorten your code and speed things up. Take the
following five lines:
> $required_fields = array();
> while ($row = mysql_fetch_array ($result)) {
> $field_name = $row['field_name'];
> array_push ($required_fields, $field_name);
> };
And turn them into these three lines:
while ($row = mysql_fetch_row($result)) {
$required_fields[] = $row[0];
}
Also note, I ditched the ";" after the "}" since it's unnecessary.
> function check_for_errors($f){
> while(list($key,$val) = each($f)) {
> if(!strlen($val) && in_array($key,$required_fields)) {
> ... snip o rama ...
> This error message pops up for every field that is blank: Warning: Wrong
> datatype for second argument in call to in_array() in /path/to/file on line 139
I'd invert your procedure here. You should loop through your $required array
and check the form's contents based on that. This protectes you against
someone altering the form and omitting a required field all together. This
also has the added benefit of only having one thing to evaluate in your if
statement.
while(list($key,$val) = each($required)) {
if(!strlen($f[$val])) {
Another thing, looks like the code that's in the check_for_errors() function
can just be stand alone code, w/o a function. This will (slightly) improve
performance.
Enjoy,
--Dan
--
PHP scripts that make your job easier
http://www.analysisandsolutions.com/code/
SQL Solution | Layout Solution | Form Solution
T H E A N A L Y S I S A N D S O L U T I O N S C O M P A N Y
4015 7 Ave, Brooklyn NY 11232 v: 718-854-0335 f: 718-854-0409