JuniorDev JuniorDev - 7 months ago 35
SQL Question

how to use a PHP variable in SQL select statement

I know this question was asked before. I have checked the old threads but without success. That's why i am posting it here again.

I have this php variable $_POST["selected-Items"] It's a result of the selected values in a drop down list in another page. For example if I selected country, order, date from the list then the result would be country,order,date

I want to extract from my SQL Server table the columns from this variable. I am using this query

$query = 'SELECT "'.$_POST['selected-Items'].'" FROM database.mytable';

Any suggestion please how to add the variable into the query in a correct way ? Thank you very much.

Answer Source

You don't have to use double quotations " for column name!

SELECT column1, column2, ... FROM table_name

if $_POST['selected-Items'] is an array you should implode it's items with ,

$arr = ["value1", "value2", "value3"];
$string = implode(", ", $arr);

After using implode the $string will be like code below and you can use it for sql:

"value1, value2, value3"

your code must be like:

$query = 'SELECT ' . $_POST['selected-Items'] . ' FROM database.mytable';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download