1

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.

11
  • 1
    print what is inside your $selval or $_POST['selectedvalue']? Commented Oct 20, 2018 at 13:46
  • 1
    And provide error text. Commented Oct 20, 2018 at 13:46
  • 1
    What are the actual column names? Commented Oct 20, 2018 at 13:47
  • 1
    If you print($lambings);exit; and copy/paste the query does it run via phpMyAdmin or mysql-workbench, etc. ? Commented Oct 20, 2018 at 13:48
  • 2
    Do you execute $lambings? What driver are you using? This is open to SQL injections. Commented Oct 20, 2018 at 13:48

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes that was it! Thanks very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.