0

I have a page where I am wanting to allow a user to select fields from a select that exist in a table, then display the contents of those fields on screen. I have set-up the select like so

<select name="queryfields" size="12" multiple="multiple" tabindex="1">
<option value="firstname">firstname</option>
<option value="lastname">lastname</option>
<option value="address">address</option>
<option value="phone">phone</option>

And I know to discover what options were selected I can use this:

<?php
    header("Content-Type: text/plain");

    foreach ($_GET['queryfields'] as $selectedOption)
        echo $selectedOption."\n";
?>

And that gives me an array of the fields selected. However, how do I then parse the array to generate my full query? For example, let's say that firstname, lastname were selected. I would then want to build my query like this:

Select firstname, lastname from employeedata

Unknown to me, is how to get the data from the array into a select statent like my above code snippet.

Kara
  • 6,115
  • 16
  • 50
  • 57
IcyPopTarts
  • 494
  • 1
  • 12
  • 25

2 Answers2

0

Try This:

$sql = '';
$selected_fields = array();   
foreach ($_GET['queryfields'] as $selectedOption){
    //echo $selectedOption."\n";
    $selected_fields[] = $selectedOption;
}
if(!empty($selected_fields)){
    $fields = implode(',', $selected_fields);
    $sql = 'SELECT '.$fields.' from employeedata'; 
}

//print query if it is not empty

if(!empty($sql)){
    echo $sql;
}
Bhaskar Jain
  • 1,651
  • 1
  • 12
  • 20
0

You can use PHP implode() function.

<?php
    header("Content-Type: text/plain");
    $q = "SELECT ".implode(', ', $_GET['queryfields'])." FROM employeedata";
?>

But there are some possibilities for SQL injection. You should read the about that before proceeding. How can I prevent SQL injection in PHP?

You can create a design like the below

<?php
    header("Content-Type: text/plain");
    $filter = array_filter($_GET['queryfields'], function($val) {
        $allowedFields = array(
            'firstname',
            'lastname',
            'address',
            'phone',        
        );
        return in_array($val, $allowedFields);
    }

    $q = "SELECT ".implode(', ', $filter)." FROM employeedata";
?>
Community
  • 1
  • 1
Sriram G
  • 369
  • 3
  • 14