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!

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 ;)

Need Your Help

Changed Discovery Behavior of Alternative MinGW in Eclipse-CDT(8.2) Bundled in Kepler-version(4.3)

mingw eclipse-cdt

When using an alternative MinGW version like e.g., mingwbuilds-gcc/g++-4.8.1, the CDT(8.2) bundled in the latest Kepler-version(4.3) is not able to discover it as a MinGW tool chain.

android custom button shape

android user-interface uibutton android-layout shape

I am a beginner. So I request you to be patient with me.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.