Using php eval

Hi,
I am wondering if this is an ok solution to my problem. So I have a table and the user selects which columns to show. This outputs in a table format.

As it outputs I need to specify the table head <th> title and then loop though the results and create a <td> for each record.

The problem is that I want to do an ‘if’ for each variable so it needs to outside the loop for the table head and inside the loop for the table cells.

This is how I am starting

‘<?php if($_GET['f_scientific_name']=='1'){ $field_head = '`Scientific name`'; $field = '`$latin_name`'; } ?>’
(ignore the ` in the variables I couldn’t get it to show on here otherwise)

So I can then echo out $field_head before the loop.
and then in the loop I do this

eval("\$field = \"$field\";"); echo $field;

Is this a bad way of doing it? Security wise I am not too concerned as the get variable is not used directly, only to turn on or off the field to be displayed.

How else could I do it if this is not a suitable solution.

thanks

enclose your code block in ```

yes. eval() is evil, period.

all you need is a map where you list which parameter has which name associated.

ah ok. So I’m not sure what you mean. Can you point me to an example at all?

I was trying to do it as above so I didn’t have to do an ‘if’ statement twice. One set for the head of the table and another for the loop. Would the way you are doing it mean I wouldn’t need to do that.

  1. From a client send an array with field names. like

     ?fields[]=scientific_name&fields[]=whatever_name
    
  2. Create an array with column titles. The keys should be the same as column names in the database

    $titles = [
    ‘scientific_name’ => ‘Scientific name’,
    ‘whatever_name’ => ‘Whatever name’,
    ];

  3. loop over the client array to output both table title and data coulmns

    echo “”;
    foreach ($fields as $col)
    {
    echo “$titles[$col]”;
    }
    echo “”;
    foreach ($data as $row)
    {
    echo “”;
    foreach ($fields as $col)
    {
    echo “$row[$col]”;
    }
    echo “”;
    }

thanks for that i’ll have a look and see how I get on. I’m finishing work now so will have to be tomorrow. Hopefully it will sink in a bit overnight and I can get it all working tomorrow.
thanks

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.