Use a variable for the LIMIT in a SELECT of MYSQL with PHP


I need to do a SELECT in PHP where X records are randomly selected. So I'm using the ORDER BY RAND() method, but I need the LIMIT to be one or the other depending on a variable, that is, something like this:

$sql = "SELECT * FROM table ORDER BY RAND() LIMIT = '$limite'";

I see that does not work, and I do not think I can do it with the "Prepared Statements". If possible, I would like you to apply your answer to the previous example, I would be much clearer.

Thank you.

asked by ByBrayanYT - Tops y más 16.11.2018 в 20:20

3 answers


The Reference Manual says that you can use a variable with LIMIT using prepared queries.

Precisely yesterday I answered about this , only that in that case it was code directly in the handler.

If it's for PHP, you can do it perfectly through prepared queries:

$sql = "SELECT * FROM table ORDER BY RAND() LIMIT ?";
if ($stmt=$mysqli->prepare($sql)){
    $stmt->bind_param("i", $limit);
    /*Verificar manejar resultados*/
    echo "Error en la consulta: ".$mysqli->error();
answered by 17.11.2018 / 01:30

You have to concatenate your variable to the String:

$sql = "SELECT * FROM table ORDER BY RAND() LIMIT ".$limite;

* Also remove the equality, since the LIMIT is directly specified the value.

answered by 16.11.2018 в 22:18

The problem is the = that is in the statement

you should use something like:

$sql = "SELECT * FROM table ORDER BY RAND() LIMIT $limite";
answered by 16.11.2018 в 20:47