Jump to content

many variable, many if statement scenario, another way?


johnseito

Recommended Posts

Hello everyone,

 

I created a form for user to fill in, this form has 10 field such as name,,

gender, birthday, country, etc.  What I want to do is have the user fill in all the fields, and if they miss 1 or 2, or 3 etc of the field, I want to mark the word next to the field red of the ones they didn't fill in and said you did not fill in all the fields.

 

the problem I have doing this is that, there is 10 variables, and so there will be a lot of IF statement combination to cover all 10 scenario, making it a lot of IF statement.

 

I was wondering if there is a efficient way of doing this.

 

Let me know of your Suggestion, and code example.

 

thanks,

 

Link to comment
Share on other sites

I'm pretty sure that's not what he meant. 

 

@Thread starter: If statements are the best way to go so that you can do special validation on names and emails.  Sure, you can do it all at once with maybe an array of the fields, but you can't really get down to exact validation without IFs.

Link to comment
Share on other sites

try

<input type="text" name="username" value="<?php echo $_POST['username'];?>">

 

if username is not set then it will be an empty text box

 

 

What does this have to do with user filling in the field or not?  please explain.

 

 

DarkWater

 

--------

 

you know what I mean right, if I was to do if statement for every scenario, there will be tons of if statement, for example with 10 variable, there is more than 10 scenario, just like a lottery ticket, if there are 7 number there is tons of combination in how to mix and match those 7 numbers.

 

 

Link to comment
Share on other sites

You could do

 

if $_POST['uname'] == '' {
$unameempty = 1;
}

if $_POST['gender'] == '' {
$genderempty = 1;
}

if $_POST['birthday'] == '' {
$birthdayempty = 1;
}

 

Then you could do

 

if $unameempty == 1 {
echo "<b>username</b>";
}
else {
echo "username";
}

if $genderempty == 1 {
echo "<b>gender</b>";
}
else {
echo "gender";
}

if $birthdayempty == 1 {
echo "<b>birthday</b>";
}
else {
echo "birthday";
}

 

Something like that should work.

Link to comment
Share on other sites

peranha---

 

that look like it might work, I did it with your concept, but code it a little differently.

 

There is a problem, one of it I came across is that, for example some fields I have values in them

to guild user to input the correct information. This makes the field not blank anymore, so

it screws up my coding logic.  Now even if a user didn't fill in this field it think it did b/c this field

is not really blank.

 

Do you know how I can get around this? 

 

I would like it that if I click in the field that is blank with values, it clears out the value. 

Do you know how I can do this?

 

thanks,

 

 

 

Link to comment
Share on other sites

using this method:

 

if $_POST['uname'] == '' {

 

can still fail. If a user just puts in a blank space for example.

 

use this rather then that:

 

if empty($_POST['uname']) {

 

and if you want to shorten the whole thing, maxudaskin has the right idea using the Ternary operator ( ? )

 

ACE

Link to comment
Share on other sites

using this method:

 

Code:

 

if $_POST['uname'] == '' {

 

 

can still fail. If a user just puts in a blank space for example.

 

use this rather then that:

 

Code:

 

if empty($_POST['uname']) {

 

 

using

if empty($_POST['uname'])
this isn't any different than if $_POST['uname'] == '' { or !$_POST['uname'],  I just tried it. 

 

if a user input blank space, it think it is not blank.

 

maxudaskin

$gender = empty($_POST['gender']) ? "Unknown" : $_POST['gender'];

 

what does this code do, I tried it and don't see any result.

Link to comment
Share on other sites

DarkWater Use Javascript to clear out the fields.

 

could you provide some javascript code example that will go hand in hand with php and mysql that will do that. 

 

I am looking for some at the moment, I am not too familiar with javascript.

Link to comment
Share on other sites

peranha---

 

that look like it might work, I did it with your concept, but code it a little differently.

 

There is a problem, one of it I came across is that, for example some fields I have values in them

to guild user to input the correct information. This makes the field not blank anymore, so

it screws up my coding logic.  Now even if a user didn't fill in this field it think it did b/c this field

is not really blank.

 

Do you know how I can get around this? 

 

I would like it that if I click in the field that is blank with values, it clears out the value. 

Do you know how I can do this?

 

thanks,

 

 

 

 

you would put in the if

 

if ((trim($_POST['birthday']) == '') || $_POST['birthday'] == 'mm-dd-yyyy') {

$birthdayempty = 1;

}

 

That will trim out all spaces and make sure it is not equal to 0 characters.  It will also check to make sure that something is filled in other than the default which I am just guessing.

 

not too good with java either, so not sure how to code that if you want to go that way.

Link to comment
Share on other sites

Here's how I usually do this:

<?php
$err_fields = array();
foreach ($_POST as $fld => $val) {
    switch ($fld) {
        case 'firstname':   // these are al the fields that must be filled in
        case 'lastname':
        case 'street':
        case 'city':
        case 'state':
        case 'zip':
              if (strlen(trim(stripslashes($val))) == 0) { //field is blank
                  $err_fields[] = $fld;
              }
              break;
        case 'something':
        case 'somethingelse':
//
//            do another validation on different content
//
              break;
     }
}
?>

 

Then when you create your form:

<?php
$flds = array('firstname','lastname','street','city','state','zip');
$tmp = array();
$tmp[] = '<form method="post" action="">';
foreach ($flds as $fld) {
    $red = (in_array($fld,$err_flds))?' style="color=red"':'';
    $val = (isset($_POST[$fld]))?htmlentities(stripslashes($_POST[$fld]),ENT_QUOTES):'';
    $tmp[] = '<label for="' . $fld . ' ' . $red . '>' . ucwords($fld) . '</label>';
    $tmp[] = '<input type="text" name="' . $fld . '" id="' . $fld . '" value="' . $val . '"><br>';
}
$tmp[] = '<input name="submit" type="submit" value="Enter the information">';
$tmp[] = '</form>';
echo implode("\n",$tmp) . "\n";
?>

 

Ken

Link to comment
Share on other sites

if ((trim($_POST['birthday']) == '') || $_POST['birthday'] == 'mm-dd-yyyy') {

$birthdayempty = 1;

}

 

using the trim works. 

 

I also think that some of you misunderstand my point, for example if I have a field coded like this

<input name="state" type="text" value ="- Enter State -"/>

 

value as "-enter state-" to guild users so they know what to input, b/c I have value

as enter state, it is not blank anymore, and even if user didn't enter anything in this field it is not blank.

 

so how do I go about solving this?  One way I can think of it, make the code equal to -enter state - and if it does means it's blank.

 

How do I do when a user click in this field with a value to clear the value and how do I make this value gray out so it makes the appearance look nicer?

 

maybe this can only be done using javascript?

Link to comment
Share on other sites

Do this:

 

<script type="text/javascript">

window.onload = initForms;

function initForms() {

  var allInputs = document.getElementsByTagName("input");

  for (var i=0;i<allTags.length;i++) {

      if (alltags.type == "text") {

            alltags.onfocus = removeVal();

      }

  }

}

function removeVal() {

        if (this.value == this.defaultValue) {

                this.value = '';

        }

}

     

 

</script>

 

I think that should work.

Link to comment
Share on other sites

Add to my version:

<?php
$default_vals = array('firstname' => '- Enter First Name -', 'lastname' => '- Enter Last Name -','state' => ' - Enter State -');
$err_fields = array();
foreach ($_POST as $fld => $val) {
    switch ($fld) {
        case 'firstname':   // these are al the fields that must be filled in
        case 'lastname':
        case 'street':
        case 'city':
        case 'state':
        case 'zip':
              if (array_key_exists($fld,$default_vals))
                      str_replace($default_vals[$fld],'',$val);   // remove the default value from the entered value
              if (strlen(trim(stripslashes($val))) == 0) { //field is blank
                  $err_fields[] = $fld;
              }
              break;
        case 'something':
        case 'somethingelse':
//
//            do another validation on different content
//
              break;
     }
}
?>

The change the form part to:

<?php
$flds = array('firstname','lastname','street','city','state','zip');
$tmp = array();
$tmp[] = '<form method="post" action="">';
foreach ($flds as $fld) {
    $red = (in_array($fld,$err_flds))?' style="color=red"':'';
    $val = (isset($_POST[$fld] && $_POST[$fld] != $default_vals[$fld]))?htmlentities(stripslashes($_POST[$fld]),ENT_QUOTES):'$default_vals[$fld]';
    $tmp[] = '<label for="' . $fld . ' ' . $red . '>' . ucwords($fld) . '</label>';
    $tmp[] = '<input type="text" name="' . $fld . '" id="' . $fld . '" value="' . $val . '"><br>';
}
$tmp[] = '<input name="submit" type="submit" value="Enter the information">';
$tmp[] = '</form>';
echo implode("\n",$tmp) . "\n";
?>

 

Ken

Link to comment
Share on other sites

Do this:

 

<script type="text/javascript">

window.onload = initForms;

function initForms() {

  var allInputs = document.getElementsByTagName("input");

  for (var i=0;i<allTags.length;i++) {

       if (alltags.type == "text") {

            alltags.onfocus = removeVal();

       }

   }

}

function removeVal() {

        if (this.value == this.defaultValue) {

                 this.value = '';

        }

}

       

 

</script>

 

I think that should work.

 

My bad, that needs to be in code tags:

<script type="text/javascript">
window.onload = initForms;
function initForms() {
  var allInputs = document.getElementsByTagName("input");
  for (var i=0;i<allTags.length;i++) {
       if (alltags[i].type == "text") {
            alltags[i].onfocus = removeVal();
       }
   }
}
function removeVal() {
        if (this.value == this.defaultValue) {
                 this.value = '';
        }
}
       

</script>

 

Link to comment
Share on other sites

kenrbnsn

 

there is an error with this part of your code.

 

 $val = (isset($_POST[$fld] && $_POST[$fld] != $default_vals[$fld]))?htmlentities(stripslashes($_POST[$fld]),ENT_QUOTES):'$default_vals[$fld]';

 

Here is a problem.

Lets say the user click on the submit button after filling in the inputs, is there a way I can retain what they inputted when they click the submit button?  For example, if there is 10 field and the user fill in 3 fields, and the rest blank, my code will highlight what they left out as blank in red, but also empty, and refresh everything the user enter before, so they have to start inputting everything again.

 

Is there a code, or a way to solve this that would retain what they inputted earlier in the field so they don't have to retype everything and continue on with what they missed?

 

Link to comment
Share on other sites

Sorry,

 

This line

<?php
$val = (isset($_POST[$fld] && $_POST[$fld] != $default_vals[$fld]))?htmlentities(stripslashes($_POST[$fld]),ENT_QUOTES):'$default_vals[$fld]';
?>

 

Should be

<?php
$val = (isset($_POST[$fld] && $_POST[$fld] != $default_vals[$fld]))?htmlentities(trim(stripslashes($_POST[$fld])),ENT_QUOTES):$default_vals[$fld];
?>

 

In answer to your other question, this part of the code (together with the above statement) takes care of putting the value back:

<?php
   $tmp[] = '<input type="text" name="' . $fld . '" id="' . $fld . '" value="' . $val . '"><br>';
?>

 

Ken

Link to comment
Share on other sites

Sorry,

 

Try this:

<?php
$val = (isset($_POST[$fld]) && $_POST[$fld] != $default_vals[$fld])?htmlentities(trim(stripslashes($_POST[$fld])),ENT_QUOTES):$default_vals[$fld];
?>

 

I had a ")" misplaced.

 

Note: when you get an error when using posted code, please post the error you get. Many times, we don't proof our scripts, so errors creep in...

 

Ken

Link to comment
Share on other sites

OK.

 

I check your most updated code, and this is the result I get from it. 

 

I went to the browse and I see nothing accept this code,

$tmp[] = '<input name="submit" type="submit" value="Enter the information">';

 

showing a button "enter the information".

 

is the output of your code not producing the expected result? 

 

Once I see that your codes are working, I will see how the put back works and try doing it that way.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.