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?

3
  • 2
    Possible duplicate of Selecting Random Rows in MySQL Commented Oct 9, 2016 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: en.wikipedia.org/wiki/SQL_injection Commented Oct 9, 2016 at 14:56
  • thnks for helping out Commented Oct 31, 2016 at 19:04

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.