code igniter SQL_CALC_FOUND_ROWS - php

How to get total number of rows for particular query and also limiting the query results to 10 rows. For example. I've a table called sample. It has 400 rows. On running a query like where name = "%Sam%" it returns me 213 rows. Now I'l be taking only first 10 rows and displaying the result to user but I need the total rows returned. How should I need to do it in code igniter?
SELECT
SQL_CALC_FOUND_ROWS *
FROM
sample
WHERE
name like "%sam%"
like this?
How to retrieve total number counts?

You need to run a second query to get the results of SQL_CALC_FOUND_ROWS:
SELECT FOUND_ROWS()
That will return the value found using SQL_CALC_FOUND_ROWS. You may find using an alias easier for getting the result, though:
SELECT FOUND_ROWS() AS num_results

You can use two query one to get the count and the other return the limited result.
Like in your model create a function that only returns the count variable
and create a second function that generates the paginated results.
eg..
public function count($where){
$query = $this->db->query("select count(id) as count from clients $where");
return $query->row('count');
}
}
public function limit($sidx,$sord,$start,$limit,$where){
$query = $this->db->query("select * from clients $where ORDER BY $sidx $sord LIMIT $start , $limit");
if ($query->num_rows() > 0){
return $query->result_array();
}
}
And here goes the controller code
$where = // calculated
$count = count($this->model->count($where));
if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; }
if ($page > $total_pages) $page = $total_pages;
$start = $limit * $page - $limit;
$users = $this->model->limit($sidx,$sord,$start,$limit,$where);
.................

Related

PHP PDO pagination foreach

I'm trying to create a pagination for my PDO query. I cant figure it out. I've tried numerous google searches, but nothing that will work for me. [I probably didn't search hard enough. I'm not sure]
This is my code:
$sql2 = "SELECT * FROM comments WHERE shown = '1'ORDER BY ID DESC";
$stm2 = $dbh->prepare($sql2);
$stm2->execute();
$nodes2= $stm2->fetchAll();
foreach ($nodes2 as $n1) {
echo "text";
}
I want to be able to limit 10 comments per page, and use $_GET['PAGE'] for the page.
Something that I tried
$sql2 = "SELECT * FROM comments WHERE shown = '1'ORDER BY ID DESC";
$stm2 = $dbh->prepare($sql2);
$stm2->execute();
$nodes2= $stm2->fetchAll();
$page_of_pagination = 1;
$chunked = array_chunk($nodes2->get_items(), 10);
foreach ($chunked[$page_of_pagination] as $n1) {
echo "text";
}
If someone could help out, I appreciate it.
You need to limit the query that you are performing, getting all values from the database and then limiting the result to what you want is a bad design choice because it's highly inefficient.
You need to do this:
$page = (int)$_GET['PAGE']; // to prevent injection attacks or other issues
$rowsPerPage = 10;
$startLimit = ($page - 1) * $rowsPerPage; // -1 because you need to start from 0
$sql2 = "SELECT * FROM comments WHERE shown = '1' ORDER BY ID DESC LIMIT {$startLimit}, {$rowsPerPage}";
What LIMIT does:
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
More information here: http://dev.mysql.com/doc/refman/5.7/en/select.html
Then you can proceed getting the result and showing it.
Edit after comment:
To get all the pages for display you need to know how many pages are there so you need to do a count on that SELECT statement using the same filters, meaning:
SELECT COUNT(*) as count FROM comments WHERE shown = '1'
Store this count in a variable. To get the number of pages you divide the count by the number of rows per page you want to display and round up:
$totalNumberOfPages = ceil($count / $rowsPerPage);
and to display them:
foreach(range(1, $totalNumberOfPages) as $pageNumber) {
echo '' . $pageNumber . '';
}

Percentage Rows from Mysql in codeigniter

Here is my model code that gets percentage of all questions in table (questions)
$public function ques()
{
#get all question count
$query= $this->db->query("SELECT * FROM questions");
$result = $query->result_array();
$count = count($result);
$limit = ($count/100)*50;
# select only limited question which set with $limit
$query= $this->db->get("Questions" , $limit);
$result = $query->result_array();
return $result;
}
There are four columns :
1. ques_id
2. question
3. exam_id
4. chapter
What I need that to get no of rows of each chapter and get percentage rows rather than to count all the questions only and returning result as shown in code. Thank you

how to get a specific id within 5 rows in a paging query in Mysql

I have a function in php I use it for paging it is like this :
$query = "SELECT id,
FROM table
ORDER BY id ASC
LIMIT $offset,5";
this work fine but what I want is to get the page that contain id number let say 10 and with it the other 4 rows, I want it to return something like this:
7,8,9,10,11,12 -> if I give it id number 10.
25,26,27,28,29 -> if I give it id number 26 and so on.
like it would return the 5 rows but I want to know how to set the offset that will get me
the page that have the 5 rows with the specified id included.
what should I do like adding where clause or something to get what I want!
Notice that the IDs in your table won't be consecutive if you delete some rows. The code below should work in such conditions:
$result = mysql_query('select count(*) from table where id < ' . $someId);
$offset = mysql_result($result, 0, 0);
$result = mysql_query('select * from table order by id limit ' . max($offset - 2, 0) . ',5');
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
Try something like this
//but for pagination to work $page should be $page*$limit, so new rows will come to your page
$limit = 5;
$start = ($page*limit) -2; // for normal pagination
$start = $page -2; // for your case, if you want ids around the $page value - in this case for id = 10 you will get 8 9 10 11 12
if ($start < 0) $start = 0; // for first page not to try and get negative values
$query = "SELECT id,
FROM rowa
ORDER BY id ASC
LIMIT $start,$limit";

PHP+MySQL: How to fetch just limited count of results?

I have a DB table with 100-200k records and I need to optimize it. For example, if a user want to search the term car, he will get around 25k results.
I would like to offer him just let's say 500 newest results, but how to do that? I know I have to use LIMIT, but I am not sure, how to "group" just the newest 500 rows.
For making a better picture how I am fetching data from database now, here's a little snippet:
$search = mysql_real_escape_string(searched_query($_GET['skill']));
$q = "...long sql query...";
echo $q;
$result = mysql_query($q);
$items = 30; // number of items per page.
$all = $_GET['a'];
$num_rows = mysql_num_rows($result);
if($all == "all"){
$items = $num_rows;
}
$nrpage_amount = $num_rows/$items;
$page_amount = ceil($num_rows/$items);
$page_amount = $page_amount-1;
$page = mysql_real_escape_string($_GET['p']);
if($page < "1"){
$page = "0";
}
$p_num = $items*$page;
// Query that you would like to SHOW
$result = mysql_query($q." ORDER BY published DESC LIMIT $p_num , $items");
Thank you in advance!
By ordering by published DESC you have already ordered the list from newest to oldest. So if you apply the limit of 500, it will automatically only fetch the newest 500 rows...
So Mysql will order first, and then apply the limit.
Use ORDER BY in the query. Have a look here for more details

Paging in php displaying data over multiple pages

Hi I am trying to display my users data over pages
Here is my code:
//Run a query to select all the data from the users table
$perpage = 2;
$result = mysql_query("SELECT * FROM users LIMIT $perpage");
It does display this the only two per page but I was wondering how you get page numbers at the bottom that link to your data
here is my updated code
$result = mysql_query("SELECT * FROM users"); // Let's get the query
$nrResults=mysql_num_rows($result); // Count the results
if (($nrResults%$limit)<>0) {
$pmax=floor($nrResults/$limit)+1; // Divide to total result by the number of query
// to display per page($limit) and create a Max page
} else {
$pmax=floor($nrResults/$limit);
}
$result = mysql_query("SELECT * FROM users LIMIT 2 ".(($_GET["page"]-1)*$limit).", $limit");
// generate query considering limit
while($line = mysql_fetch_array( $result ))
{
?>
error
Parse error: syntax error, unexpected $end in E:\xampp\htdocs\Admin.php on line 98
In order to do this you also need to use the offset value in your SQL Statement, so it would be
SELECT * FROM users LIMIT $offset, $perpage
Example:
SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15
Then to get the links to put on the bottom of your page you would want to get a count of the total data, divide the total by the per page value to figure out how many pages you are going to have.
Then set your offset value based on what page the user clicked.
Hope that helps!
Update:
The unexpected end most likely means that you have an extra closing bracket } in your code which is causing the page to end and still has more code after it. Look through your code and match up the brackets to fix that. There are a few other issues in the code sample you pasted.
$result = mysql_query("SELECT * FROM users" ); //Note if you have a very large table you probably want to get the count instead of selecting all of the data...
$nrResults = mysql_num_rows( $result );
if( $_GET['page'] ) {
$page = $_GET['page']
} else {
$page = 1;
}
$per_page = 2;
$offset = ($page - 1) * $per_page; //So that page 1 starts at 0, page 2 starts at 2 etc.
$result = mysql_query("SELECT * FROM users LIMIT $offset,$per_page");
while( $line = mysql_fetch_array( $result ) )
{
//Do whatever you want with each row in here
}
Hope that helps
You can then use the nrResults number to figure out how many pages you are going to have... if you have 10 records and you are displaying 2 per page you would then have 5 pages, so you could print 5 links on the page each with the correct page # in the URL...
Use requests ! http://php.net/manual/en/reserved.variables.request.php
if (((isset($_GET['page'])) AND (is_int($_GET['page']))) {
$perpage = $_GET['page'];
}
$result = mysql_query("SELECT * FROM users LIMIT $perpage");
...
Link http://yourwebsite.com/userlistforexample.php?page=3
or
http://yourwebsite.com/userlistforexample.php?somethingishere=21&page=3

Categories