-7

I wrote this piece of code in PHP.

$result = mysqli_query($connection, "SELECT * FROM app WHERE" . $_REQUEST['filter']  . " ORDER BY " . $_REQUEST['sort']);

$output = array();
while($row = mysqli_fetch_array($result)) {
    $record = array();
    $record['app_id'] = $row['app_id'];
    $record['app_name'] = $row['app_name'];

    $output[] = $record;
}

I want to use LIMIT as well.

When i usen LIMIT at ..... " ORDER BY " . $_REQUEST['sort'] "LIMIT 3"); it gives me this error: filter =1=1 sort = 1=1

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in ....service.php on line 80

How can I do that? Thank you in advance

sajad
  • 1
  • 4
  • You are open to SQL injections with this code. If `$_REQUEST['filter']` is a string this query is invalid as well. Have you tried adding `limit` to your query? You also missed concatenation here, `$_REQUEST['filter'] " ORDER BY "` So I suspect you aren't using error reporting/checking logs. – chris85 Nov 19 '15 at 11:51
  • Yes i've used LIMIT at the end of this code but it didn't work – sajad Nov 19 '15 at 11:53
  • This is not a PHP question, you could read more about mysql queries itself: http://dev.mysql.com/doc/refman/5.7/en/select.html – Markomafs Nov 19 '15 at 11:53
  • Did you read my whole comment? You should include your attempt to use limit. – chris85 Nov 19 '15 at 11:53
  • @Markomafs he does have PHP errors in this code. – chris85 Nov 19 '15 at 11:54
  • probably because of $_REQUEST['filter']. in a where statement you should use field and values – Markomafs Nov 19 '15 at 11:54
  • you should more about into: http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php/60496#60496 – Markomafs Nov 19 '15 at 11:56
  • OP should check error logs/enable reporting. Should be getting `Parse error: syntax error, unexpected '" ORDER BY "' (T_CONSTANT_ENCAPSED_STRING)` so there is no mysql usage yet.. – chris85 Nov 19 '15 at 11:57
  • I've edited my post with the error it gave – sajad Nov 19 '15 at 12:02
  • Show your working code, the non working code, and what values are being passed in. I don't see how `$_REQUEST['filter']` is going to work unless you are passing raw SQL to this page...(bad idea). – chris85 Nov 19 '15 at 12:09
  • I gave 1=1 to filter and 1=1 to sort – sajad Nov 19 '15 at 19:24

1 Answers1

1

Append it to the query like this:

mysqli_query($connection, "SELECT * FROM app WHERE" . $_REQUEST['filter'] " ORDER BY " . $_REQUEST['sort'] . " LIMIT 1,1");
tino.codes
  • 1,512
  • 1
  • 12
  • 23