MySQL Query selecting too many rows - php

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

Related

Like doesn't work properly with limit?

hello guys I have problem with mysql like and limit command when used together they return 0 null I tried this in my php then I go to test it inside phpmyadmin I get the same result here is the code
//mysql
SELECT * FROM `items` WHERE name like '%php%' LIMIT 9,9; //this return null
SELECT * FROM `items` WHERE name like '%php%' LIMIT 9 OFFSET 9; //this return null
SELECT * FROM `items` WHERE name like '%php%';//this return some results
//this is weird please help here is the php code that I use
//php
$db = DB::getInstance();
$results = $db->query("SELECT * FROM `items` WHERE name LIKE ? LIMIT {$start},9",array("'%{$search}%'"));//the query function does the bindvalue
//$start come form $_GET['page'];
//$start equation // $start = ($_GET['page'] * $perpage) - $perpage
//the $perpage is always 9 cause I want to display 9 always or less
//and for sure I check for them if they were set , empty , and escape them etc...
$results = $results->results();
printItems($results);//a function that print items in a special way
You do not say how many results you get when you have no limit set, but I assume it's less than 9?
The LIMIT 9,9 or LIMIT 9 OFFSET 9 sets a limit of 9 results total, but starts looking from result number 9. If there are less than 9 results, you will get 0 results returned. I'm guessing you have misunderstood the offset-part of the limit clause (which aren't needed).
Remove the OFFSET-part, and you'll get a result back, even with LIMIT present.
Ensure you have enough data that satisfy LIMIT 9, 9
LIMIT 9, 9 means retrieve rows from 10 to 18

Fetch 5 records again and again from data base

I am developing an android app where i want to fetch 5 records each time using this query.
SELECT *from contest_table WHERE created_by='$me' LIMIT 5;
Now i get 5 records , but i want to fetch more 5 (next) records from data base when i click on "FETCH-MORE-RECORD" button inside the app
You can use OFFSET :
SELECT * from contest_table WHERE created_by='$me' LIMIT 5,5;
This will return 5 more rows, from position the 6th row (6-10).
The first number is to declare the start position of the fetch, and the second one is two declare how many to fetch.
This could also be written like this:
SELECT * from contest_table WHERE created_by='$me' LIMIT 5 OFFSET 5;
You will have to give a limit start and range. It will look as follows:
SELECT *from contest_table WHERE created_by='$me' LIMIT 5, 5;
To get first 5 records
SELECT * from contest_table WHERE created_by='$me' LIMIT 0,5;
To get next 5 records
SELECT * from contest_table WHERE created_by='$me' LIMIT 6,5;
Like wise you can change the starting point increasing it by 5.
So here is the solution. You need to keep the track of the off. So delcare a static variable for store the off. also update the offset after every click so next time you get right result.
public static int offset=5;
Then use this query with your listener;
SELECT * from contest_table WHERE created_by='$me' LIMIT 5,5;
It's a simple logic, Which I am representing as PHP codes, You request for first page from android by including page 1. in URL
http://SITENAME.COM/index.php?task=articles&page=1
You grab the result coming from URL like here
$page = $_GET['page'];
$max = 5; //As you want to retrieve 5 results only
And here define $start from where to start retrieving values
$end = $page * $max;
$start = $end+1 - $max;
Your query will be like
SELECT * FROM table order by column desc limit $start, $max //start will be 1 and max value to retrieve will be 5
After that you request page 2 and URL will be
http://SITENAME.COM/index.php?task=articles&page=2
and again in the query $start will be 6 and max value to retrieve will be 5 that is $max
Hope this helps, This is what the logic behind pagination.

how to get last 10 and then show random 5

hello all i am a php developer and right now i am having a simple issue like i want to get the last 10 data out of my database table and then show random 5 out of them .
like see the code below.
$random=rand(0,18);
mysqli_query(
$connection,
"SELECT something1,something2
FROM `table`
where (id !='0')
ORDER BY time DESC
LIMIT 4 OFFSET $random");
this query selects last 4 updated fields randomely out of 18 but i want a something better solution to this
First, define "the last 10"; for now let's assume the last ten when ordered by time. So, that is in fact the first ten when I order them the order way (I guess you got that):
SELECT * FROM `table` WHERE (id != '0') ORDER BY time DESC LIMIT 10;
then we subselect that to randomize and limit:
SELECT * FROM (
SELECT * FROM `table` WHERE (id != '0') ORDER BY time DESC LIMIT 10;
) A ORDER BY RAND() LIMIT 5
Remember, your database is extremely powerful and fast, use it for any data-processing.
Not sure there is a great solution with Select. Your sample take 4 line in a row with an OFFSET which is not a truly random selection. You should limit your select to 10 and then get 5 row of the 10 by another php code.
$rows = mysqli_query($connection,
"SELECT something1,something2 FROM `table` where (id !='0')
ORDER BY time DESC LIMIT 10");
//then, get 5 random key from your array of row from the mysql select
$rand_keys = array_rand($rows, 5);
In case you prefer randomizing in PHP, you can use PHP's shuffle and array_slice.
<?php
$last_10_rows = mysqli_query($connection, "simple query to get last 10 rows");
shuffle($last_10_rows); // randomize the array
$random_5_rows = array_slice($last_10_rows, 0, 5); // take first 5
?>
For

LIMIT in php sql not working

Hello everyone i would like to ask you why, when i put limit 0,5 and 5,10 it does not work correctly here is my code.
$sql = mysql_query("SELECT * FROM vn_questions WHERE published = 1 limit 0,5 ");
while($data=mysql_fetch_array($sql))
{
echo $data['author'];
}
it gives me 5 results but when i put
$sql = mysql_query("SELECT * FROM vn_questions WHERE published = 1 limit 5,10 ");
while($data=mysql_fetch_array($sql))
{
echo $data['author'];
}
it gives me 6 .. where is the problem and how Can i fix it? I tried +1 -1 but the output is not working correctly.
the syntax for MYSQL LIMIT is LIMIT OFFSET COUNT, so what your second query is saying is start at record 5, and show me 10 results. does your table only have 6 records in it? since that's less than 10 it will only show those 6 available.
From the SQL manual
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):
AND
With one argument, the value specifies the number of rows to return from the beginning of the result set:

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