unknown
unknown

Reputation: 109

dynamic populate SELECT statement with variables

I have a table with 7 columns populated from mysql... the table headers each contain a checkbox which if checked and clicked on submit will be sent to a export to csv page.

Is there a way to use the SELECT $var1, $var2...$var7 FROM... ? $var1 to $var7 will be used if checkbox checked and if no checkbox checked then display some message

To betted understand what i am asking i'll put some code...

HTML

<td class="captabel">
 <input type="checkbox" value="expid" >
</td>
<td class="captabel">
 <input type="checkbox" value="exploc" >            
</td>
etc

php

if(isset($_POST['expid'])){
$expid="id";
}
else{
$expid="";
}
if(isset($_POST['exploc'])){
$exploc="locatie";
}
else{
$exploc="";
}
etc

and at some point comes the SELECT * FROM table... <-- this is what i want to replace with SELECT $expid, $exploc ... FROM table... i have tried various ways and none worked. Thanks.

Upvotes: 0

Views: 41

Answers (3)

unknown
unknown

Reputation: 109

Solved it.

Based on Dipanwita Kundu answer i used

if(!empty($columns)){
    $sql = 'SELECT '. implode(', ', $columns). ' FROM raport' ;
}   

and works like a charm. Thank you.

Upvotes: 0

Dipanwita Kundu
Dipanwita Kundu

Reputation: 1667

  1. Modify your input type <input type="checkbox" name="exploc" value="exploc">
  2. In your php script check :

    $selectStr= "";
    if(!empty($_POST['expid'])) {
      $selectStr="id";
    }
    else{
     $selectStr="";
    }
    if(!empty($_POST['exploc'])) {
      $selectStr= !empty($selectStr) ? ", locatie" : "locatie";
    }
    else{
     $selectStr="";
    }
    

so your query will be

    if(!empty($selectStr)) {
      $qry = "SELECT $selectStr FROM table...";
     }

Instead of setting different name you can set array type name in <input type="checkbox" value="exploc" name="exploc[]">

Upvotes: 1

meda
meda

Reputation: 45500

You have to use the name attribute on your checkbox

<input type="checkbox" value="123" name="expid" />

Upvotes: 1

Related Questions