Syntax error on pagination - php

This should be a fairly straight forward question. I am getting a Warning: mysql_num_rows() expects parameter 1 to be resource, boolean error and I can't figure out the correct syntax. Using mysqlerror I am getting You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-5, 5' .
Any help would be great. The code is part of a pagination that I am adding.
Snippet of affected code
<?php
//Number of items to display per page
$perpage = 5;
if(isset($_GET["page"]))
{
$page = intval($_GET["page"]);
}
else
{
$page = 1;
}
$calc = $perpage * $page;
$start = $calc - $perpage;
$result = mysql_query("select * from products Limit $start, $perpage");
$rows = mysql_num_rows($result);
echo mysql_error();
if($rows)
{
$i = 0;
while($post = mysql_fetch_array($result))
{
?>

$start cannot be negative (and it is). You should make sure, that $page is not less than 1. This should fix your problem:
<?php
//Number of items to display per page
$perpage = 5;
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
if ($page < 1)
{
$page = 1;
}
$calc = $perpage * $page;
$start = $calc - $perpage;
$result = mysql_query("select * from products Limit $start, $perpage");
$rows = mysql_num_rows($result);
echo mysql_error();
if($rows)
{
$i = 0;
while($post = mysql_fetch_array($result))
{
?>

when you're using LIMIT the value of the starting point should be greater or equal to zero.
LIMIT

Related

PDO pagination query not executed correctly?

I'm currently trying to make some pagination work, but without any success.
The first query I'm executing is to grab all the data needed: so first result should be on the first page, second result on the second and so on... But I'm always getting the first result. Although I copied the query into phpmyadmin to manualy set the query and there it showed me the right results.
Here's the code where everything is happening. I'm stuck why it won't work.
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$limit = 1;
$start = 0;
$query = $db->prepare("SELECT * FROM `users` LIMIT $limit OFFSET $start");
$query->execute();
$result = $query->fetchAll(PDO::FETCH_OBJ);
$count = count($result);
$query2 = $db->prepare("SELECT * FROM `users`");
$query2->execute();
$result2 = $query2->fetchALL(PDO::FETCH_OBJ);
$count2 = count($result2);
// Pagination
$total = ceil($count2 / $limit);
if ($page > 1) {
$start = ($page - 1) * $limit;
}
if ($page != $total) {
$next_page = '<li>»</li>';
} else {
$next_page = '<li class="disabled">»</li>';
}
if ($page > 1) {
$previous_page = '<li>«</li>';
} else {
$previous_page = '<li class="disabled">«</li>';
}
What am I doing wrong?
You are doing nothing with $page. $start is always 0 in the query.
You're going to need to define how many records you want per page, then multiply that by $page -1, e.g.
$start = ($page - 1) * $records_per_page;

Jqgrid Pagination not working due to query

I am trying to set up a jqgrid and I am having difficulty in constructing the controller that generates the json data to populate the grid. I am using codeigniter 2.0+ and I am not sure how to build the query for php in codeigniter.
I followed this guid under "Loading Data -> JSON Data" for the jqgrid. I also consulted codeigniter docs on data selection. The thing is I am not sure how to write the second query to sort and limit according to the jqgrid paramiters. Here is my controller.
public function applicantdata(){
$page = $this->input->get('page');// get the requested page
$limit = $this->input->get('rows');// get how many rows we want to have into the grid
$sidx = $this->input->get('sidx');// get index row - i.e. user click to sort
$sord = $this->input->get('sord');// get the direction
if(!$sidx){ $sidx =1; }
$this->db->select('*');
$this->db->from('applicant');
$this->db->join('transaction', 'transaction.applicant_id = applicant.id');
$query = $this->db->get();
$count = $query->num_rows();
$limit = 10;
if( $count > 0 ) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages){ $page=$total_pages; }
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
//NOT SURE HOW TO DO THIS IN CODEIGNITER ENVIRONMENT
//$SQL = "SELECT a.id, a.invdate, b.name, a.amount,a.tax,a.total,a.note FROM invheader a, clients b WHERE a.client_id=b.client_id ORDER BY $sidx $sord LIMIT $start , $limit";
//$result = mysql_query( $SQL ) or die("Couldn t execute query.".mysql_error());
$result = $query->result_array();
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i=0;
foreach ($result as $myrow){
$responce->rows[$i]['id']=$myrow['id'];
$responce->rows[$i]['cell']=array($myrow['id'],$myrow['firstname'],$myrow['lastname'],$myrow['amount'],$myrow['status']);
$i++;
}
echo json_encode($responce);
}
With the above code, the grid is populating and its is working to a greater extent. Only thing is the pagination stuff not working properly in that the data on page one shows when I move to page 2, 3, etc.
Her is the final working thing. For anyone who may need it.
public function applicantdata(){
$page = $this->input->get('page');// get the requested page
$limit = $this->input->get('rows');// get how many rows we want to have into the grid
$sidx = $this->input->get('sidx');// get index row - i.e. user click to sort
$sord = $this->input->get('sord');// get the direction
if(!$sidx){ $sidx =1; }
$this->db->select('firstname');
$this->db->from('applicant');
$this->db->join('transaction', 'transaction.applicant_id = applicant.id');
$query = $this->db->get();
$count = $query->num_rows();
if( $count > 0 ) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages){ $page=$total_pages; }
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
$this->db->select('*');
$this->db->from('applicant');
$this->db->join('transaction', 'transaction.applicant_id = applicant.id');
$this->db->order_by("applicant.id", $sord);
$this->db->limit($limit, $start);
$query2 = $this->db->get();
$result = $query2->result_array();
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i=0;
foreach ($result as $myrow){
$responce->rows[$i]['id']=$myrow['id'];
$responce->rows[$i]['cell']=array($myrow['id'],$myrow['firstname'],$myrow['lastname'],$myrow['amount'],$myrow['status']);
$i++;
}
echo json_encode($responce);
}

Unsupported operand types in

I found this error in the error log file "Unsupported operand types in (and then it shows the directory and file which gave the error)". Then it says on line 28. Line 28 on my PHP page reads:
$start = ($page -1) * 5;
This might not be enough information, but please give feedback on what else I should provide to help me out.
Use the intval function on the variable $page. Also, you may want to check the $start variable for a negative value.
Like so:
function getScenes($page)
{
$total = 0;
$pages = 0;
$start = (intval($page) - 1) * 5;
if ($start < 0) {
$start = 0;
}
$query = $this->db->query("SELECT count(iId) as total FROM scenes ");
$scene = $query->result();
$total = $scene[0]->total;
if ($total) {
$pages = ceil($total / 5);
}
$q = $this->db->query("SELECT * FROM scenes ORDER BY iId DESC LIMIT $start,5");
$result = $q->result();
if (count($result)) {
return array(
'pages' => $pages,
'scenes' => $result
);
} else {
return false;
}
}

Paging in php mysql

I'm trying to make a website with movies in it, everything is fine but i have just 1 little problem,when ever i make a website, i do all work in my local computer test it then I upload the web, the code below is for paging with query it works fine in WAMP (locally). But when I upload the paging code to my web server it says NOT EXIST.
it shows the else part,whats the problem?
<?php
$per_page = 35;
$page = 1;
if (isset($_GET['page']))
{
$page = intval($_GET['page']);
if($page < 1) $page = 1;
}
$start_from = ($page - 1) * $per_page;
$con= mysql_connect("localhost","sarya_asad","Thisisfor123");
mysql_select_db('saryaal_com_movies',$con);
$current_items = mysql_query( "SELECT * FROM `english` LIMIT $start_from, $per_page");
if( mysql_num_rows($current_items) > 0)
{
while($item = mysql_fetch_assoc($current_items))
{
?>
<tr>
<td> <strong><a href="english/english-preview.php?id=<?php echo$item['id']?>" ><?php echo $item['title'] ;?></a> </strong></td>
<td> <strong> <?php echo $item['year'] ;?> </strong></td>
<td> <strong> <?php echo $item['quality'] ;?> </strong> </td>
</tr>
<tr><td>
<?php
}
}
else
{
echo 'this page does not exists';
}
$total_rows = mysql_query("SELECT COUNT(*) FROM `english`");
$total_rows = mysql_fetch_row($total_rows);
$total_rows = $total_rows[0];
$total_pages = $total_rows / $per_page;
$total_pages = ceil($total_pages); # 19/5 = 3.8 ~=~ 4
for($i = 1; $i <= $total_pages; ++$i)
{
echo "<a href='temp2.php?page=$i' class='pagNumActive'>$i</a> ";
}
?>
<?php if($Strkeyword=="" AND $StrLoc=="" AND $StrMinsal=="-1" AND $StrMaxsal=="-1" AND $StrMax_exp=="maximum" AND $Strcategory=="" AND $Strjobtype=="") {
$sql=mysql_query("select * from job where AND status='Active'");
}
$per_page = 5;
$page = 1;
if (isset($_GET['page'])) {
$page = intval($_GET['page']);
if($page < 1) $page = 1;
}
$start_from = ($page - 1) * $per_page;
if($Strkeyword=="" AND $StrLoc=="" AND $StrMinsal=="-1" AND $StrMaxsal=="-1" AND $StrMax_exp=="maximum" AND $Strcategory=="" AND $Strjobtype=="")
{
$current_items=mysql_query("select * from job LIMIT $start_from, $per_page"); } $start_from, $per_page");
if( mysql_num_rows($current_items)>0) { while($arr=mysql_fetch_array($current_items)) {
?>
<?php include("include/result.php") ?>// result u want to display
<?php
}
} else {
echo 'Data does not exists'; }
if($Strkeyword=="" AND $StrLoc=="" AND $StrMinsal=="-1" AND $StrMaxsal=="-1" AND $StrMax_exp=="maximum" AND $Strcategory=="" AND $Strjobtype=="") {
$total_rows=mysql_query("select COUNT(*) from job where AND status='Active'");
}
$total_rows = mysql_query("SELECT COUNT(*) FROM job");
$total_rows = mysql_fetch_row($total_rows);
$total_rows = $total_rows[0];
$total_pages = $total_rows / $per_page;
$total_pages = ceil($total_pages);
# 19/5 = 3.8 ~=~ 4
echo "<div style='margin-left:280px;'>";
echo "Page : ";
for($i = 1; $i <= $total_pages; $i++) {
echo "[<a style='text-decoration:none' href='search_result.php?page=$i' class='pagNumActive'>$i</a> ]";
}
echo "</div>";
?>
This is your problem:
$con= mysql_connect("localhost","sarya_asad","Thisisfor123");
mysql_select_db('saryaal_com_movies',$con);
You need to change the host details. localhost is the local server on your machine.
change this
$start_from = ($page - 1) * $per_page;
to
$start_from = ($page) * $per_page;
you might want to use something like:
$per_page = 35;
$start_from = $page * $per_page - $per_page;
Try this logic for pagination:
Your goal is to offset by the number of images you want to display on each page.
So let's say you want to display 6 movie thumbnails on a page... You'd have:
$videos_per_page = 6
$pageNumber = (isset($_GET['page']) ? ($_GET['page']) : 1);
And your offset would be:
$offset = $videos_per_page * $pageNumber
(6 videos * page 0... so you're offsetting 0 videos. That's good because you want to display the first 6 videos in your data structure on page 0).
So now that you have your offset value... You need to set your array pointer to the correct spot... Loop through your database rows storing your movies and move your pointer by your offset value... Store that in $videos_to_offset...
while ($videos_per_page < $offset && ($row = $Query_Result->fetch_assoc())) {
$videos_to_offset++;
}
Now you can loop through your database rows, outputting your videos from wherever your offset array pointer left off:
$video_counter = 0;
while ($video_counter < $videos_per_page && ($row = $Query_Result->fetch_assoc())) {
echo $row['videopath'];
$video_counter++;
}
Something like that.

PHP Paging Not Updating Results

I am creating a page that lists celebrities on Twitter. The page displays 10 different results as it should for the first loop but it doesn't seem to update the $result to pull the next 10 values from the database (for the next set of pages etc).
<?php
// connect to the database
$con = mysql_connect("localhost","someuid","somepwd");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("celebrity_twitter", $con);
$result = mysql_query("SELECT * FROM celebrities");
// number of results to show per page
$per_page = 10;
$total_results = mysql_num_rows($result);
$total_pages = ceil($total_results / $per_page);
// check if the 'page' variable is set in the URL (ex: view-paginated.php?page=1)
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = $_GET['page'];
// make sure the $show_page value is valid
if ($show_page > 0 && $show_page <= $total_pages)
{
$start = ($show_page -1) * $per_page;
$end = $start + $per_page;
}
else
{
// error - show first set of results
$start = 0;
$end = $per_page;
}
}
else
{
// if page isn't set, show first set of results
$start = 0;
$end = $per_page;
}
// display data in table
echo "<table class='table table-striped'>";
echo "<tr> <th>Avatar</th> <th>Celebrity Name</th> </tr>";
// loop through results of database query, displaying them in the table
for($i = $start; $i < $end; $i++ && $row = mysql_fetch_array($result) )
{
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) { break; }
// echo out the contents of each row into a table
echo "<tr>";
echo "<td><img height='73' width='73' src=" . "http://api.twitter.com/1/users/profile_image?screen_name=" . $row['avatar'] . "&size=bigger></td>";
echo "<td><a href=" . $row['url'] . " target='_blank'>" . $row['uid'] . "</td></a>";
echo "</tr>";
}
// close table>
echo "</table>";
// display pagination
echo "<strong>Page: </strong>";
for ($i = 1; $i <= $total_pages; $i++)
{
echo "<a href='index.php?page=$i'>$i</a> ";
}
?>
I'm using this at the moment and it's working perfectly fine for me, I hope it works for you too : PHP Pagination
You are not positioning yourself in the database, you always read the first elements:
// loop through results of database query, displaying them in the table
for($i = $start; $i < $end; $i++ && $row = mysql_fetch_array($result) )
{
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) { break; }
The proper way of doing this would be using the LIMIT clause of MySQL, with a special clause for recovering the true number of records
SELECT SQL_CALC_FOUND_ROWS * FROM celebrities LIMIT $start, $resultsperpage;
SELECT FOUND_ROWS(); // This is number of celebrities
This means that you need to calculate $start "before" running the query, i.e., "before" you know whether $start is a valid start at all. So you have to prepare for the case in which no rows are returned.
A quick alternative, which is pretty wasteful, is to retrieve everything and display only wanted rows:
// loop through results of database query, displaying them in the table
for ($i = 0; $i < $total_results; $i++)
{
$row = mysql_fetch_array($result);
if ($i < $start) continue;
if ($i == $end) break;
LIMIT implementation
mysql_select_db("celebrity_twitter", $con);
// number of results to show per page
$per_page = 10;
// We REALLY ought to move on to PDO: mysql_* will be deprecated sooner or later
$query = mysql_query('SELECT SQL_CALC_FOUND_ROWS * FROM celebrities');
// check if the 'page' variable is set in the URL (ex: view-paginated.php?page=1)
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = (int)$_GET['page'];
// make sure the $show_page value is valid
if ($show_page > 0)
$start = ($show_page -1) * $per_page;
else
$start = 0;
$query .= " LIMIT $start, $per_page;";
$paged = True;
}
else
{
$paged = False;
// The query having no LIMIT, it will retrieve everything
// if (!$paged), later we will display a link "Show Paged".
}
// Now run the query
$result = mysql_query($query);
// Also fetch REAL number of rows in table {{{
$exec = mysql_query("SELECT FOUND_ROWS() AS results;");
$tuple = mysql_fetch_assoc($exec);
$results= $tuple['results'];
mysql_free_result($exec);
unset($exec, $tuple);
// }}}
// If paging, calculate page number. Later, if ($paged), we'll display the pager.
if ($paged)
{
$maxpages = ceil($results / $per_page);
if ($page > $maxpages)
$page = $maxpages+1; // We fetch nothing.
else
$page = floor($start / $per_page)+1;
}
// display data in table. It is best to calculate $html first
// and then output it all together at end if no error.
$html = "<table class='table table-striped'>";
$html .= "<tr> <th>Avatar</th> <th>Celebrity Name</th> </tr>";
// loop through results of database query, displaying them in the table
// Here, we get all and only good results, so we need not check anything
while($row = mysql_fetch_array($result))
{
// echo out the contents of each row into a table
$html .= "<tr>";
}

Categories