0

I want to retrieve data from my table. Data should come at random and in limit.

The following code limits data:

$sql = "SELECT * FROM `products` ORDER BY id LIMIT ".$_GET["start"]." , ".$_GET["end"].";"; 

However, I want it random, how should I do it?

Bizley
  • 17,392
  • 5
  • 49
  • 59
  • 2
    Possible duplicate of [Selecting Random Rows in MySQL](http://stackoverflow.com/questions/1283640/selecting-random-rows-in-mysql) – Fragment Oct 09 '16 at 14:38
  • Assuming the user of your script can pass arbitrary strings via the `start` and `end` variable, your code is dangerously vulnerable by SQL injections: https://en.wikipedia.org/wiki/SQL_injection – chtz Oct 09 '16 at 14:56
  • thnks for helping out – Akash Desai Oct 31 '16 at 19:04

1 Answers1

0

Try doing this:

Create a function that cleans user input:

function cleanInput($input) {
  $input= trim($input);
  $input= strip_tags($input);
  $input= htmlspecialchars($input);
  return $input;
}

Then do the query:

$start  = cleanInput($_GET['start']);
$end    = cleanInput($_GET['end']);

//Using prepared statements
$sql= "SELECT * FROM `products` 
       ORDER BY rand() 
       LIMIT ?,?";

$stmt=  $conn->prepare($sql);


$row= $stmt->execute([$start,$end]);

That should do it