开发者

MySQL Query selecting too many rows

开发者 https://www.devze.com 2023-03-13 02:38 出处:网络
I am开发者_运维问答 trying to only select the difference between $from and $to and have those rows outputted in descending order. The problem so far is that I am inputting \'5\' in as the $from value

I am开发者_运维问答 trying to only select the difference between $from and $to and have those rows outputted in descending order. The problem so far is that I am inputting '5' in as the $from value and '10' into the $to value, but it seems to be outputting 10 rather than 5.

Please could you tell me where I am going wrong?

$query = mysql_query("SELECT * FROM `Posts` WHERE `isPublic` = 'yes' ORDER BY `date` DESC LIMIT $from,$to") or die(mysql_error());  


It's not FROM and TO, it's FROM and HOWMANY.


Check this out: SELECT MySQL documentation.

What you are doing by LIMIT 5, 10 is a synonym to LIMIT 10 OFFSET 5 (get 10 results skipping 5 results from the beginning of the set returned by database).


MySQL limit works such that if you provide only 1 value, it limits the number of entries to that. If you provide to values, the first one is the index where to start, and the second one the number of entries to show. If you wish to show entries from 5 to 10, you need to pass the second variable as $to-$from, like this:

$query = mysql_query("SELECT * FROM `Posts` WHERE `isPublic` = 'yes' ORDER BY `date` DESC LIMIT $from,".($from-$to)) or die(mysql_error()); 


Your $to variable is actually $length...

So you're telling it to start at record 5 and display 10 more.


You misunderstand how LIMIT works. It expects the row offset first (the starting row number), and then the number of rows you want to return, now the ending row number. Instead use

$from = 5;
$to = 5;

However, that's confusing to think of the second value as $to when it's really the number of rows. Call it $numrows instead for clarity.


The 2nd limit parameter is how many you want.

$difference = $to- $from;

LIMIT $from, $difference

This will output $difference rows starting from $from.


First parameter is the offset, second one is the actual limit. So if you want to skip first 5 results and show next 10, you need to have LIMIT 5, 10

0

精彩评论

暂无评论...
验证码 换一张
取 消