0

i am trying to use the following select query in my php code where all var1,var2,var3,var4,var5 are array variables but its not working

 $sql="SELECT SNo,Date,FROM_TIME,TO_TIME,$var1,$var2,$var3,$var4,$var5 
 FROM $table_name 
 WHERE Date='$start_date'";
Milen
  • 8,322
  • 7
  • 40
  • 55

1 Answers1

0

You can build your mysql select query using array value by this way

<?php 
$columnArray=array('column1'=>'value1',
        'column2'=>'value2', 
        'column3'=>'value3',
        'column4'=>'value4');
        //print_r($columns);
         $columns = implode(',',array_keys($columnArray));
        if(count($columnArray)>0)
         $comma=',';
        else 
          $comma='';

       $sql="SELECT SNo,Date,FROM_TIME,TO_TIME" .$comma." $columns
          FROM tableName
          WHERE Date='2014-06-22'";
        print $sql; //final query
        ?>
Always Sunny
  • 32,751
  • 7
  • 52
  • 86
  • You can simplify this a bit and don't specify keys ('column1', 'column2', ...) in array because `join` will join values not keys anyway. Also there is comma after $columns in SQL making it not valid. And one more thing - if $columnArray will be empty, then you don't need comma after TO_TIME too. – DarkSide Jun 22 '14 at 12:31
  • Thanks for you comment @DarkSide – Always Sunny Jun 22 '14 at 13:05