zan
zan

Reputation: 355

post variable in mysql query

I'd like to use the post variable value in my sql query to sort data in order chosen by a user. The table gets displayed correctly with appropriate fields but the values are not sorted.

I'm aware this is subject to sql injection, however, I'm doing this for training purposes on my local server.

<?php
$sort_in = $_POST['SortIn'];

$sql = 'select * from db.Runner order by "'.$_POST['SortIn'].'"';
    $result = mysql_query($sql, $con);

    if($result)
    {
        echo "<table border = '1'>
        <tr>
        <th>RunnerID</th>
        <th>EventID</th>
        </tr>";

        while($row = mysql_fetch_array($result))
        {
            echo "<tr><td>";
            echo $row['RunnerID'];
            echo "</td><td>";
            echo $row['EventID'];
            echo "</td><td>";
            </tr>";
        }
        echo "</table>";
?>

Upvotes: 2

Views: 6401

Answers (2)

CompuChip
CompuChip

Reputation: 9232

You are currently producing and running a query like

select * from db.Runner order by "fieldname";

which should of course be either of

select * from db.Runner order by fieldname;
select * from db.Runner order by `fieldname`;  -- for MySql
select * from db.Runner order by [fieldname];  -- for MSSQL

(I suggest one of the last two, depending on your database, in case your field name happens to be "order", for example).

Remove the double quotes

$sql = 'select * from db.Runner order by '.$_POST['SortIn'];

and possibly replace them by the appropriate delimiter, e.g.

$sql = 'select * from db.Runner order by `'. $_POST['SortIn'] . '`';

You already mentioned SQL injection and mysql_ vs mysqli_ so I'll keep my mouth shut today ;) Although I don't really see a reason - even for a training project on localhost - not to do it right, to be honest.

[edit]After posting this answer, some useful comments were made to your OP by MarcB and to the other answer by zan. Despite this being training, please heed them, as they are good advice!

Upvotes: 5

Ronald Swets
Ronald Swets

Reputation: 1667

You actually sorting on a string instead of a field, remove the quotes in the query:

$sql = 'select * from db.Runner order by '.$_POST['SortIn'];

P.S. I won't start a rant about the injection ;)

Upvotes: 1

Related Questions