user3925824 user3925824 -4 years ago 94
MySQL Question

Can Existing MySQL Query Be Modified?

I have a query early in a script that sets a limit.

Example:

$row = mysqli_query($db,"SELECT id FROM table ORDER BY id DESC LIMIT 5");


The "5" is always correct - but there's a plugin I'm building that needs to change the limit from "5" to "2" (a one-off special circumstance).

I can change $row to a new query, before the function to get the result is called - but I'd rather change the existing query.

Something like:

$row .= "LIMIT 2"


Or:

$row += "LIMIT 2"


Or:

$row < "LIMIT 2"


Of course none of those work - It's probably not possible as the query is set - but it can't hurt to ask.

Thanks all




Just a quick note - these are two separate files. File A sets the correct query based on environment and houses the function that uses the query.. File B calls the function which outputs the query (therefore I can change the query before the function call in File B). Yes, there's a reason it's setup this way.

Answer Source

You're on the right track but you have to change the query string before feeding it in the function. So make a variable for it

$query = "SELECT id FROM table ORDER BY id DESC ";

Then, however you wish, make something that adds that limit to this. In my example, an if statement

if ($this == "this") {
  $query .= "LIMIT 5";
} else {
  $query .= "LIMIT 2";
}

And then feed it to mysqli

$row = mysqli_query($db, $query);

EDIT

I read your note and your comment. Since you're calling the function from two different files, you can add a default parameter like:

function yourFunction($limit = 5) {
  $query = "SELECT id FROM table ORDER BY id DESC " . $this;
  $row = mysqli_query($db, $query);
}

By default, just calling yourFunction() without any parameters, it will do the default, in your case 5.

In that special case where you want a limit of 2, just call the function with that 2 as the parameter.

yourFunction(); // This will do the limit of 5

yourFunction(2); // This will do 2

This also make is a free-for-all so you can use whatever limit you want

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download