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.

$sort_in = $_POST['SortIn'];

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

        echo "<table border = '1'>

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


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!

Need Your Help