开发者

How to shorten php code, in multiple combination of form result

I have a php page that contains a form with 7 drop down boxes. The problem is that the 0 to 6 boxes may be unselected.

It would be a lot of work to make a switch with a case for every combination.

What other meth开发者_Go百科od can i use?

thanks, Sebastian

EDIT

For each combination i have to make different queries that contain only the selected items from the drop-boxes.

Ex. If the user selects 3 from the 7, the query has to pass 3 conditions.

EDIT2 I don't know what the values of the drop-boxes are. Because they are built up using an mysql query in a while statement

SOLUTION

I've found a solution that should work. I haven't tested it yet. First of all i want to check if what is selected in the drop-boxes. `If($_POST[telefon]="empty"){$tel=""}

else{$tel="WHERE telefon =' "}`

after this i can concatenate the $tel string with the $_POST['telefon'] string. $query_tel=$tel.$_POST['telefon']." ' ";

Final query string would look like this $query="SELECT * table ".$query_telefon." ,".$query_ziua....(and so on)

Of course i have to be very careful with the query that will result, for missing commas, apostrophes and so on. But i guess it's the simplest way.


UPDATED

ASSUMPTION: the point here is you want reduce code in relation with number of query!

PREMISE: the use of switch or and/if are both valid approach anyway!

  • for reducing your code to one line for all the queries, your SQL column name and SELECT html element should be called the same, like:
t_apple VARCHAR(255) NOT NULL,
t_peach VARCHAR(255) NOT NULL, 
t_strawberry VARCHAR(255) NOT NULL,
... 

<select name="t_apple"></select>
<select name="t_peach"></select>
<select name="t_strawberry"></select>
...

try this:

if ( isset($_POST['submit']) ) {
    $form_button = array_pop($_POST); //remove the submit button val
    $new_array = array_filter( $_POST , 'strlen'); //remove empty value from $_POST
    foreach( $new_array as $key => $val ) {

     //optionaly make some other check here if ($val != '---')

    // "INSERT INTO {$key} VALUES ( {$val} )"
    
    }
}


You can decide to preset the values and then overwriting them:

$array(
    'dropdown1' => 'value1',
    'dropdown2' => 'value2',
    'dropdown3' => 'value3',
    'dropdown4' => 'value4',
    'dropdown5' => 'value5',
    'dropdown6' => 'value6'
)

$array = $_POST;

This way you can set the default values and just overwrite the array with the post array send from the form.

EDIT: if you set the empty value to 'empty' like this:

<select name="dropdown[dropdownnamehere]">
    <option value='empty'>---</option>
</select>

You will be able to loop trough the values and only select the set ones

foreach($_POST['dropdown'] as $item => $value)
{
    if($value != 'empty')
    {
        //create a mysql part here
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜