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.

James Z
  • 12,209
  • 10
  • 24
  • 44
Rachel Watson
  • 212
  • 2
  • 9
  • 1
    print what is inside your `$selval` or `$_POST['selectedvalue']`? – A l w a y s S u n n y Oct 20 '18 at 13:46
  • 1
    And provide __error text__. – u_mulder Oct 20 '18 at 13:46
  • 1
    What are the actual column names? – Nick Oct 20 '18 at 13:47
  • 1
    If you `print($lambings);exit;` and copy/paste the query does it run via phpMyAdmin or mysql-workbench, etc. ? – ivanivan Oct 20 '18 at 13:48
  • 2
    Do you execute `$lambings`? What driver are you using? This is open to SQL injections. – user3783243 Oct 20 '18 at 13:48
  • I am using a dropdown, is it still prone to MySQL injections? @user3783243 – Rachel Watson Oct 20 '18 at 13:55
  • 1
    @RachelWatson Yes, a user doesn't even need to use the form. They could run a `curl` to your form's `action`'s value and send any value they want. Rough example `curl --data "selectedvalue=n1\` union all select password from users where role='admin'--" http://example.com/process.php` – user3783243 Oct 20 '18 at 13:56
  • mysql_escape_string will help? @user3783243 – Rachel Watson Oct 20 '18 at 14:00
  • 1
    @RachelWatson Nope, you are passing a column name, not a value. You need to check that value against a whitelist of valid column names. Use `in_array` and create an array of column names. (Also if you are using the `mysql_` driver you should stop that, you wont be able to use parameterized queries which is what should be used when you are passing values) – user3783243 Oct 20 '18 at 14:01
  • @user3783243 I am new to programming, could you suggest an e-resource which would help me find out more? – Rachel Watson Oct 20 '18 at 14:08
  • 1
    Take a look at this thread, https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php, and this answer for your current example https://stackoverflow.com/a/8255054/3783243 – user3783243 Oct 20 '18 at 14:11

1 Answers1

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.

Prasinus Albus
  • 406
  • 1
  • 3
  • 21