# PHP -> SQL Injection & more



## DeathByTray (Apr 15, 2010)

1) Am I right assuming this code below will prevent SQL injections?

```
if (isset($_GET['col']) && isset($_GET['sort']))
	{
	$orderby = $_GET['col'];
	$sortby = $_GET['sort'];

	if (!get_magic_quotes_gpc())
		{
		addslashes($orderby);
		addslashes($sortby);
		}
	}
```

2) My imaginary table:

Table:


A|B|C
1a|1b|1c
2a|2b|2c
Since I'd like to have a sort function I added a link to each header eg.: www.localhost/test?col=a&sort=asc
This would obviously sort the table by A ascending but what if I'd like to sort it descending? Every time I sort the table I'd have to change the link of the header. This would require a lot of ifs:

```
if ($sortby == "asc") $h_sort = "&sort=desc";
else $h_sort = "&sort=asc";
if ($orderby == A) $header_url_A = "?col=A".$h_sort;
elseif ($orderby == B) $header_url_B = "?col=B".$h_sort;
elseif ($orderby == C) $header_url_C = "?col=C".$h_sort;
```

Any better way around this?


----------



## W1zzard (Apr 15, 2010)

for sorting i usually do

$order='';
if ($_GET[sort]=='columna')
  $order=' ORDER BY columna';
if ($_GET[sort]=='columnb')
  $order=' ORDER BY columnb';
if ($_GET[reversesort]==1)
  $order=$order.' DESC';

and in the SQL string just insert $order, no need for escaping because any injections are filtered out by the == string comparisons


----------



## DeathByTray (Apr 15, 2010)

Your code is used for SQL queries.
What I'm trying to do is change the url of the table header.


```
<a href="www.localhost/test<?echo $header_url_A;?>">A</a>
<a href="www.localhost/test<?echo $header_url_B;?>">B</a>
<a href="www.localhost/test<?echo $header_url_C;?>">C</a>
```

Or did I miss something?


----------

