Darshan Suryawanshi Darshan Suryawanshi - 15 days ago 7
SQL Question

Is there any way to represent COLUMN NAME with a Variable in SQL-query?

Is there any way to represent a column name of table with a variable?

Like in below example, in Switch - case: DATE, instead of writing column(visit_date), I want to use variable $d_status.
Thanks in Advance.

$s_id = mysql_prep($s_id);
$d_status = "visit_date";
$searchby = mysql_prep($searchby);
$searchtext = mysql_prep($searchtext);

$query = "SELECT * ";
$query .= "FROM doctor ";
$query .= "WHERE (s_id = $s_id ) AND (d_status = '{$d_status}') ";

switch ($searchby){
case 'd_name':
$query .= "AND ( d_name = '{$searchtext}' )";
break;
case 'd_id':
$query .= "AND ( d_id = $searchtext )";
break;
case 'DATE':
$query .= "AND ( $d_status = '{$searchtext}' )";
break;
Default: null;
break;
$result = mysqli_query($connection, $query);
confirm_query($result);
return $result;
}

Answer

In PHP is allowed use a variable for a case value (not often used but allowed) (in others language like c++ not)

  $myTets = 'DATE'
  switch ($searchby){
      ....
      case $myTest:
         echo 'Test OK';
         break;
      .....

or if you need a dinamic column name contained in $d_status you can use string concat

$query .= "AND ( " . $d_status ." = '{$searchtext}' )";