Force Limit on User MySQL Query - php

So I have an area where people can write their own query against my database, but I want to limit the returned results (much like PhpMyAdmin).
So I need to check $_POST['query'] to see if has a limit statement, if it does, make sure it's under 30, say. If there is no limit, I need to add it.
How would I do this?

Ignoring risks ... I think the best is to use the query as a subquery and apply limit. So you avoid evaluating the query .
SELECT *
FROM (
SELECT *
FROM 'table'
LIMIT 0 , 100
) AS query
LIMIT 0 , 30

You can use preg_* functions to check the query and inject your preferred limit.
EDIT: I totally ignored possible uses of the LIMIT keyword. Here's the edited version.
$query = 'SELECT * FROM aa LIMIT 100,20';
$limit = 20; // predefined max limit
// possibilities:
// LIMIT N[,N]
// LIMIT N OFFSET N
preg_match('~(?<=\blimit\s)\s*(?<limit>\d+)\s*(,\s*\d+|\soffset\s+\d+)?\s*$~i',$query,$limitStr);
if (isset($limitStr['limit'])) {
$maxLimit = min((int)$limitStr['limit'],$limit);
// user might have already limited it so this is
// just to make sure it does not exceed your max.
$query = preg_replace('~(?<=\blimit\s)\s*\d+\s*(,\s*\d+|\soffset\s+\d+)?\s*$~i',$maxLimit.'$1',$query);
} else $query .= " LIMIT $limit";
echo $query;
will output SELECT * FROM aa LIMIT 20,20

Related

PHP & MySQL - Limiting an array

I'm trying to limit the array mysql_fetch_assoc($query), and am unsure on how I would go about it.
$query = mysql_query('SELECT * FROM table ORDER BY id DESC');
while($output = mysql_fetch_assoc($query))
{
//do something
}
Do you add a counter or something? How do you add this counter?
I'm really confused about mysql_query and mysql_fetch_assoc. Please Help!
After your ORDER BY id DESC, add LIMIT 100 (or whatever number you want). For the next 100 rows, use LIMIT 100,100, then LIMIT 200,100 and so on.
You can limit the results directly in the SQL query. To get the top 100 records do
SELECT * FROM table
ORDER BY id DESC
LIMIT 100
Use LIMIT
SELECT * FROM table ORDER BY `id` DESC LIMIT 10;
Haven't you seen phpMyAdmin always limiting to 30?

SQL to only fetch some rows?

It was some time ago I worked with PHP, MySQL and SQL, so I need some help. In my table I have 44 rows, but I only want to get 24 of them. Before I have just loaded all the rows like in the code below, and now I need some help to modify it to only load 24 rows. Thanks!
$query = "SELECT * FROM {$tableObject} {$sort1};";
$res = $mysqli->query($query);
$row_cnt = mysqli_num_rows($res);
while($row01 = $res->fetch_object()) {
// Some other code here
}
Use this in your query:
LIMIT 24
LIMIT is a MySQL function that selects a particular range of results from your query results. There are basically two ways of using it:
By simply specifying the number of results you want to fetch, like LIMIT 24; or
By specifying another range in the form of LIMIT X, Y. Where X is the beginning and Y is number of rows you want to fetch, like: LIMIT 10,5 that would select the 5 results from row 11 to 15
In your particular case you can simply replace this line:
$query = "SELECT * FROM {$tableObject} {$sort1};";
For:
$query = "SELECT * FROM {$tableObject} {$sort1} LIMIT 24;";
or even:
$query = "SELECT * FROM {$tableObject} {$sort1} LIMIT 0,24;";
For a better understanding about how to use limit, I recommend you to read this page from MySQL manual

Limit FOREACH in MySQL PDO query

I am using the below code to try and echo out the latest 5 entries on the MySQL table, I cannot, however seem able to figure how to limit the number of results, can anyone help me out by allowing me to limit the number of results to 5 rows?
<table>
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/resources/pdo.php");
$q = "SELECT * FROM `content` ORDER BY `id`";
$query = $pdo->query($q);
$data = array_reverse($query->fetchAll());
foreach ($data as $row) {
echo "<tr><td>{$row['title']}</td><td>{$row['id']}</td></tr>";
}
?>
</table>
Thanks!
Please note that I am new to PHP and I need help so if this question isn't useful, help me because I have only just started this.
Use LIMIT clause in your SQL query:
SELECT * FROM `content` ORDER BY `id` DESC LIMIT 5
From the manual:
The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).
With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):
Use the LIMIT word:
SELECT * FROM `content` ORDER BY `id` DESC LIMIT 5
order by id desc to get rid of the array_reverse and limit 5 to cap the number of returned results.
$q = "SELECT * FROM `content` ORDER BY `id` DESC LIMIT 5";
...
$data = $query->fetchAll();
As a global guideline: when writing queries try to formulate them in such a way that the resultset is as close to what you need as possible, ie no extra sorting or filtering operations afterwards.
having the dbserver send data that you aren't going to use is a waste
having to resort/refilter data on the webserver costs webserver performance and, in the case of big resultsets, it can cost lots of memory as well
When pulling data from a database you normally set a LIMIT via the MySQL-query, instead of counting the loop-iterations when reading the returned data.
$q = "SELECT * FROM `content` ORDER BY `id` LIMIT 5";

Select a Random Database Row WHERE ID=a random value created by PHP function

If I have a PHP function that generates a random number, is it possible to pass that variable into the sql statement in the WHERE clause? I'm using CodeIgniter, so this is my code using its syntax.
$random = rand(1, 572);
$result = $this->db->query( ' SELECT part1, part2, _id FROM `questions` WHERE `_id` >= '$random' LIMIT 0,1 ');
Is this even possible to do?
EDIT: The reason I want the php to execute the random number is because I need to call it multiple times throughout my pages, and it needs to do another call to another database using a sql query
Yes it is possible if you concatenate the variable with the string:
$query = "SELECT
part1,
part2,
_id
FROM
questions
WHERE _id >= " . $random . " LIMIT 0,1";
$result = $this->db->query($query);
But if what you want is to select a random row, then you might want this query
SELECT part1, part2, _id FROM questions ORDER BY RAND() LIMIT 1
EDIT
I understand that _id will be random, but you are specifying the min and max for rand(), right? So you'd have to change it whenever you insert a new row, or you'd have to use two queries if you want to make sure rand() does not return a value too high. By using ORDER BY RAND() you are free from both problems. You simply have to get the value of _id that was returned from the query.
This might just be a mater of using double quotes instead of single quotes on the outside of your string.
$result = $this->db->query("SELECT part1, part2, _id FROM `questions` WHERE `_id` >= '$random' LIMIT 0,1 ");
Try this:
$result = $this->db->query("SELECT part1, part2, _id FROM questions WHERE _id >= '".$random."' LIMIT 0,1 ");

How to browse results with php mssql?

I'm working with php and I want to do a next button that's step to the next 10 records (like when you browse question with stackoverflow)
I don't know how to do that but I'm thinking to do it with Top n record ? Do you think that's a good idea ? Any suggestion?
As for doing it in PHP, you can easily make the button send a POST or GET request for the starting amount. For instance, a user would make the initial request and that is just yoursite.com/search.php, and the next button would send them to the same page with the same search criteria only send an additional field of "start", (i.e. yoursite.com/search.php?start=10). And in the code, you can simply check for it:
if(isset($_POST['start'])) {
//code to add to the search string to start at $_POST['start']
}
Edit 1: This article is the best I could find as to how to replicate MySQL's LIMIT function. Also, this one has a more definitive query to reference, but it's the same idea.
I know in MySQL you can use LIMIT X, Y where X is the lower bound of the return and Y is the upper bound. So if you wanted to return 10-20 you would use LIMIT 10, 20. Not sure what the MS-SQL equivalent is.
doesn't mssql have something like LIMIT in mysql? so you could do:
select xxx from yyy LIMIT 0,10
for first 10 results, then do LIMIT 10,20 for next 10 results etc.
You can use MySQL's limit
Set a variable called:
$limit = 10;
$pl = $_GET["page"] * $limit;
if(!isset($_GET["page"]) || $_GET["page"] == 1)
{
$pl = 0;
}
and in your query do
$sql = sprintf("SELECT * FROM table LIMIT %d,%d"
mysql_real_escape_string($pl),
mysql_real_escape_string($limit));
Btw this is from memory but i think it works.
Would this be any help to you?
$count=$_POST[page]*10;
for MySQL:
$rowsPerPage = 10;
$offset = ((int)$_GET['page'] - 1) * $rowsPerPage;
$result = mysql_query(
sprintf('select xxx from yyy LIMIT %d,%d', $offset, $rowsPerPage)
);

Categories