Rachel Watson
Rachel Watson

Reputation: 212

php $_POST variable as column name in mysql query

I have created a dropdown menu and wish to use the variable so acquired to select a column in MySQL query. I have used the following code:

<select name="selectedvalue">
    <option value="n1">Birthweight</option>
    <option value="n2">3-month weight</option>
    <option value="n3">6-month weight</option>

</select>

Later I am retrieving the variable using

$selval = ($_POST['selectedvalue']);

MySQL query:

$lambings = "Select year, `".($_POST['selectedvalue'])."` as weight from mytable 
      GROUP by year(dob)";

but the sql query fails every time.

Upvotes: 1

Views: 334

Answers (1)

Prasinus Albus
Prasinus Albus

Reputation: 416

The problem is not the variable, but the query itself. You can use group by only when you have count/ averages etc in your query.

either change that or remove the group by part in your query.

Upvotes: 1

Related Questions