Jump to content

how to limit the result using PHP , without using LIMIT clause when fetching rows in database query?


sasori
Go to solution Solved by sasori,

Recommended Posts

let's say i have a an object...it contains 100 objects/array..and then in it's sql query, I didn't use offset nor limit.

my question now is, is there are way to manipulate the returned result using only PHP to display only like e.g 24 objects/array ?

my objective is, I wanna paginate based on 24 result and not with 100 ..so how?

 

 

 

 

Link to comment
Share on other sites

You'll want to run a query like:

$count_result=$mysqli->query("SELECT count(*) FROM tbl_name");

which will return the total row count (ie 100) then you can divide that by the number of results per page.  Once you have that you can run additional queries using:

SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name LIMIT $start, $perpage

where the starting record is the next record after the last query (say 20 per page). First time through $start = 0 and $perpage = 20. The next time through, $start = 21, $perpage = 20. 

 

Sorry left out a critical part, $count_result is used to define $perpage.  So in the 100/20 example, you would generate 5 pages with 20 results each.

Edited by rwhite35
Link to comment
Share on other sites

  • Solution

you can paginate an array using array_slice(). the second and 3rd parameters, offset and length, operate the same as the LIMIT operands do in a query.

 

same suggestion as other developers to whom I have asked from...

 

but anyway...I have solved my issue on my own by just adding a simple if statement

 

 

$container = array();
foreach($hugeObject as $k => $obj){
    if(isset($obj[$obj->USERID])){
       continue;
     if(count($container) < 24)
     $container[$obj->USERID] = $obj;
}
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.