I am doing pagination for the first time and run into a problem. The problem appears to be on the line where I have while with mysqli_fetch_array. Error says this: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given...
Here is my code with the whole pagination part. Thanks!
if (!(isset($page_num))) {
$page_num = 1;
}
$sqlko = mysqli_query($con, "SELECT * FROM clanek INNER JOIN uzivatel ON clanek.uzivatel_ID=uzivatel.uzivatel_ID");
$rows = mysqli_num_rows($sqlko);
$rows_num = 5;
$last = ceil ($rows/$rows_num);
if($page_num < 1) {
$page_num = 1;
} else if($page_num > $last) {
$page_num = $last;
}
$max = 'limit ' .($page_num - 1) * $rows_num .',' .$rows_num;
$vytah = mysqli_query($con,"SELECT * FROM clanek INNER JOIN uzivatel ON clanek.uzivatel_ID=uzivatel.uzivatel_ID $max ORDER BY clanek_ID DESC ");
while($clanecky = mysqli_fetch_array($vytah)){
if($clanecky["typ_ID"] == "1") {
$nadpis_alpha = $clanecky["nadpis"];
$nadpis = urldecode($nadpis_alpha);
$obsah = $clanecky["obsah"];
$uzivatel_ID = $clanecky["uzivatel_ID"];
$jmeno = $clanecky["jmeno"];
$prijmeni = $clanecky["prijmeni"];
$datum = $clanecky["datum"];
$novinka_ID = $clanecky["clanek_ID"];
echo "<div class='domu_column'>";
echo "<h2><a href='index.php?page=novinka&id=$novinka_ID&nazev=$nadpis'>".$nadpis."</a></h2>";
echo "<div id='novinka_panel'><b>".$jmeno." ".$prijmeni."</b> | ";
echo $datum."</div>";
echo "<p>".$obsah."</p>";
echo "Stránka $page_num z $last";
if ($page_num == 1) {
} else {
echo " <a href='{$_SERVER['PHP_SELF']}?page=domu&page_num=1'> <<-First</a>";
echo " ";
$predchozi = $page_num - 1;
echo " <a href='{$_SERVER['PHP_SELF']}?page=domu&page_num=$predchozi'> <<-Předchozí</a>";
}
echo "----";
if ($page_num == $last) {
} else {
$next = $page_num + 1;
echo " <a href='{$_SERVER['PHP_SELF']}?page=domu&page_num=$next'>Next -></a> ";
echo " ";
echo " <a href='{$_SERVER['PHP_SELF']}?page=domu&page_num=$last'>Last ->></a> ";
}
echo "</div>";
}}
LIMIT (variable $max) must be last in SQL-query. However, you inserted before ORDER BY. See SELECT Syntax.
$max = 'limit ' .($page_num - 1) * $rows_num .',' .$rows_num;
$vytah = mysqli_query($con,"SELECT * FROM clanek INNER JOIN uzivatel ON clanek.uzivatel_ID=uzivatel.uzivatel_ID $max ORDER BY clanek_ID DESC ");
Change to:
$vytah = mysqli_query($con,"SELECT * FROM clanek INNER JOIN uzivatel ON clanek.uzivatel_ID=uzivatel.uzivatel_ID ORDER BY clanek_ID DESC $max ");
Related
I want to read the different ID on different page, by using the prev/next button.
If I click next button, I want to get the next ID, if I click previous button, it will back to the previous ID. Following is what I want.
Example:
testnext_pre1.php?id=1&page=1
testnext_pre1.php?id=2&page=2
testnext_pre1.php?id=5&page=3
Here is my problem. As you can see, I get the same ID on every page because of my code. How to get the correct ID for the page?
Please take note: the IDs are not increase by sequence, as some contents might be deleted. So I don't want the answer something like "+1".
$rowsPerPage = 1;
if(isset($_GET['page']))
{
$pageNum= $_GET['page'];
}
else
{
$pageNum = 1;
}
// preceding rows
$previousRows =($pageNum - 1) * $rowsPerPage;
$query = "SELECT * FROM news LIMIT $previousRows, $rowsPerPage";
$result = mysql_query($query) or die('Error couldn\'t get the data').mysql_error();
echo "<table border=1>\n";
echo "<tr><th>ID</th><th>Name</th><th>Password</th><th>Perm</th><th>Email</th>
<th>Date</th></tr>";
// print the results
while(list($id,$name,$pass,$perm,$email,$date) = mysql_fetch_array($result))
{
echo "<tr><td>$id</td><td>$name</td><td>$pass</td><td>$perm</td><td>$email</td>
<td>$date</td></tr>";
}
echo '</table>';
$query = "SELECT COUNT(id) AS numrows FROM news";
$result = mysql_query($query) or die('Error, couldn\'t get count title=\"$page\"').mysql_error();
$row = mysql_fetch_assoc($result);
$numrows = $row['numrows'];
$lastPage = ceil($numrows/$rowsPerPage);
$phpself = $_SERVER['PHP_SELF'];
if ($pageNum > 1)
{
$page = $pageNum - 1;
$prev = "<div class=\"paginationbtn floatleft\">previous</div>";
$first = " [First Page] ";
}
else
{
$prev = ' previous ';
$first = ' [First Page] ';
}
if ($pageNum < $lastPage)
{
$page = $pageNum + 1;
$resultid = mysql_query("SELECT id FROM news");
while($loopid=mysql_fetch_array($resultid))
{
$rowid = $loopid['id'];
$next = " <div class=\"paginationbtn floatright\">next</div> ";
}
}
else
{
$next = ' [Next] ';
}
echo $prev . " " . $next;
Just get the previous and next ids from the database
if ($pageNum > 1)
{
//Get previous id using this query
SELECT id FROM news LIMIT $previousRows-1, $rowsPerPage
}
if ($pageNum < $lastPage)
{
//Get next id using this query
SELECT id FROM news LIMIT $previousRows+1, $rowsPerPage
}
Try the following sql query to get the next id,right now you are looping the news table and your next button will always have the same value
if ($pageNum < $lastPage)
{
$page = $pageNum + 1;
$resultid = mysql_query("select id from news where id = (select min(id) from news where id > ".$_GET['id'].")");
while($loopid=mysql_fetch_array($resultid))
{
$rowid = $loopid['id'];
$next = " <div class=\"paginationbtn floatright\">next</div> ";
}
$prevresultid = mysql_query("select id from news where id = (select max(id) from news where id < ".$_GET['id'].")");
while($loopid=mysql_fetch_array($prevresultid))
{
$rowid = $loopid['id'];
$prev= " <div class=\"paginationbtn floatleft\">next</div> ";
}
}
Note: you will need mysqli and prepared statements to secure your code
if you want to set pagination than no need of next id it will mange by query only . and in query we change only offset .
for e.g each page display 3 records so our limit is 3
now if we on first page than our fetch record query is(on first page offset is always 0)
so offset is 0 and limit is 3
SELECT fieldName FROM tableName LIMIT offset,limit
for second page now current offset is 3 so
prev is current_offset minus limit (3-3) so prev offset is 0
next is current_offset plus limit (3+3) so next offset is 6
now in 3rd page current offset is 6
prev is current_offset minus limit (6-3) so prev offset is 3
next is current_offset plus limit (6+3) so next offset is 9
try this one
<?php
$rowsPerPage = 1;
if(isset($_GET['page']))
{
$pageNum= $_GET['page'];
}
else
{
$pageNum = 1;
}
// preceding rows
$previousRows =($pageNum - 1) * $rowsPerPage;
$query = "SELECT * FROM news LIMIT $previousRows, $rowsPerPage";//offset,limit
$result = mysql_query($query) or die('Error couldn\'t get the data').mysql_error();
echo "<table border=1>\n";
echo "<tr><th>ID</th><th>Name</th><th>Password</th><th>Perm</th><th>Email</th>
<th>Date</th></tr>";
// print the results
while(list($id,$name,$pass,$perm,$email,$date) = mysql_fetch_array($result))
{
echo "<tr><td>$id</td><td>$name</td><td>$pass</td><td>$perm</td><td>$email</td>
<td>$date</td></tr>";
}
echo '</table>';
$query = "SELECT COUNT(id) AS numrows FROM news";
$result = mysql_query($query) or die('Error, couldn\'t get count title=\"$page\"').mysql_error();
$row = mysql_fetch_assoc($result);
$numrows = $row['numrows'];
$lastPage = ceil($numrows/$rowsPerPage);
$phpself = $_SERVER['PHP_SELF'];
if ($pageNum > 1)//current page > 1
{
$page = $pageNum - 1;
$prev = "<div class=\"paginationbtn floatleft\">previous</div>";
$first = " [First Page] ";
}
else
{
$prev = ' previous ';
$first = ' [First Page] ';
}
if ($pageNum < $lastPage)
{
$page = $pageNum + 1;
$next_row=$previousRows+1;
$resultid = mysql_query("SELECT id FROM news LIMIT $next_row,1");
while($loopid=mysql_fetch_array($resultid))
{
$rowid = $loopid['id'];
$next = " <div class=\"paginationbtn floatright\">next</div> ";
}
}
else
{
$next = ' [Next] ';
}
echo $prev . " " . $next;
my default load page is ok with next and prev results.. but for search results i can get only first page then blank for the next page. let say total search results row is 9, it display 3 pages with next link. but when i click the next link, it queries no result on the page 2. here is my code:
echo '<table><tr><td>';
echo '<form method="post" name="frmSearch" action="mypage.php>
Search by name
<input type="text" name="txtSearch">
<input type="submit" name="submit" value="Search">
</form>';
$per_page = 5;
$page = 1;
if (isset($_GET['page']))
{
$page = intval($_GET['page']);
if($page < 1) $page = 1;
}
$start_from = ($page - 1) * $per_page;
$Prev_Page = $page - 1;
$Next_Page = $page + 1;
if (!$_POST){
//$sql = "SELECT * FROM mytable LIMIT $start_from, $per_page";
//$totalr = mysql_query("SELECT COUNT(*) FROM mytable");
//$totalr = mysql_fetch_row($totalr);
//$totalr = $totalr[0];
//$total_pages = $totalr / $per_page;
//$total_pages = ceil($total_pages);
//$listresult = mysql_query($sql);
//$total = mysql_num_rows($listresult);
}
else {
if ($_POST['txtSearch']!="") {$cond1 = " name LIKE
'%".$_POST['txtSearch']."%' ";} else {$cond1 = 1; }
$sql = "SELECT * FROM mytable WHERE ".$cond1." LIMIT $start_from, $per_page";
$totalr = mysql_query("SELECT COUNT(*) FROM mytable WHERE name LIKE
'%".$_POST['txtSearch']."%' ");
$totalr = mysql_fetch_row($totalr);
$totalr = $totalr[0];
$total_pages = $totalr / $per_page;
$total_pages = ceil($total_pages);
$listresult = mysql_query($sql);
$total = mysql_num_rows($listresult);
}
if($total == 0){
echo "<center>No records found.</center>";
}
echo "<span style='float:right;margin-top:8px;'>[ <a href='new.php'>Add New</a>
]</span></td></tr>";
echo "<table>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
";
while ($_POST = mysql_fetch_assoc($listresult)){
echo "<tr>";
echo "<td>" . $_POST['id'] . "</td>";
echo "<td>" . $_POST['name'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo "</table>";
echo $totalr." result";
echo "<br>";
if ($Prev_Page) {
echo " <a href ='{$_SERVER['PHP_SELF']}?page=$Prev_Page'><< Prev</a> ";
}
if ($totalr > $per_page) {
for($i = 1; $i <= $total_pages; ++$i)
{
echo "<a href='{$_SERVER['PHP_SELF']}?page=$i'>$i</a> | ";
}
}
if ($page!=$total_pages) {
echo " <a href='{$_SERVER['PHP_SELF']}?page=$Next_Page'>Next >></a> ";
}
maybe you need to use SELECT COUNT(*) FROM mytable WHERE name LIKE '%$search%' ... remember to escape the $_POST['txtSearch']
I'm having an issue with pagination. I've debugged as mush as I can and it seems there is an issue with the SELECT query and execution. If I take out the pagination part the query executes and displays all entries in a long table. I tried executing an array, bindValue and bindParam but nothing works, can anyone see what I'm missing?
function showEmployees() {
$count = $this->dbh->query("SELECT * FROM employee_info");
$count->rowCount();
$count = $count->rowCount();
// if ($count > 0) {
// echo "The total amount of employees is " . $count;
// } else {
// echo "There are no records in this table.";
// }
$page_rows = 10;
$last_page = ceil($count / $page_rows);
echo $last_page;
if ($last_page < 1) {
$last_page = 1;
}
$page_num = 10;
if (isset($_GET['pn'])) {
$page_num = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
if ($page_num < 1) {
$page_num = 1;
} elseif ($page_num > $last_page) {
$page_num = $last_page;
}
$limit = 'LIMIT ' .($page_num -1) * $page_rows .', '. $page_rows;
$query = $this->dbh->prepare("SELECT * FROM employee_info ORDER BY employee_id DESC :page_limit");
$query->bindParam(':page_limit', $limit );
$query->execute();
$t = "<table name='displayEmployees' border='1' >";
$t .="<tr>";
$t .= "<th>Employee ID</th>";
$t .= "<th>First Name</th>";
$t .= "<th>Last Name</th>";
$t .= "</tr>";
while($u = $query->fetch(PDO::FETCH_ASSOC)) {
$t .="<tr>";
$t .= "<td>{$u['employee_id']}</td>";
$t .= "<td>{$u['first_name']}</td>";
$t .= "<td>{$u['last_name']}</td>";
$t .="</tr>";
}
$t .="</table>";
return $t;
}
It think it's the way you handled the limit although that should have tripped an error.
Try:
$beginLimit = ($page_num-1)*$page_rows;
$endLimit = $page_rows;
$query = $this->dbh->prepare("SELECT * FROM employee_info ORDER BY employee_id DESC LIMIT :begin,:end");
$query->bindValue(':begin',(int)$beginLimit,PDO::PARAM_INT);
$query->bindValue(':end',(int)$endLimit,PDO::PARAM_INT);
$query->execute();
You can't include keywords as parameters to your prepared statements. You'll need to do this:
$limit = 'LIMIT ' .($page_num -1) * $page_rows .', '. $page_rows;
$query = "SELECT * FROM employee_info ORDER BY employee_id DESC ".$limit;
$query->query($query);
Note: because the parameters are already sanitised by your script you can trust them, so the benefit of a prepared statement is largely lost in this case.
This is my script for the paging on my site when the user clicks on a league.
The league is then echoed to the screen, and if the league is over 3 rows then it splits it up in to several pages.
What I am doing after is depending on where the user is in the league (the SQL query is using ORDER BY the total points column in the table), e.g if the user is on page one of the league table then for it to display that page first, but if the user is on page 3 of the league table then for that page to displayed first.
Does anyone know a way in order for me to achieve this?
//Recently updated from answer
$sql="SELECT members.username, members.total_points FROM members, members_leagues WHERE members.username = members_leagues.username AND
members_leagues.sub_league = '$chosenleague' ORDER BY members.total_points DESC";
$result=mysql_query($sql);
$i = 0;
$found = false;
$team_position = 0;
while (!$found && $row = mysql_fetch_row($result)){
if ($row[username] == $_SESSION[username]) {
$team_position = $i;
$found = true;
}
$i++;
}
$rowsPerPage = 3;
$pageNum = ceil($i/$rowsPerPage);
//end of recently updated
if(isset($_GET['page']))
$pageNum = $_GET['page'];
$offset = ($pageNum - 1) * $rowsPerPage;
$counter = $offset + 1;
$query = " SELECT members.username, members.teamname, members.total_points, FROM members, members_leagues WHERE members.username = members_leagues.username AND members_leagues.sub_league = '$chosenleague' ORDER BY members.total_points DESC " . " LIMIT $offset, $rowsPerPage";
$result = mysql_query($query) or die('Error, query failed');
echo "<h3 style=\"color:red;\">$chosenleague</h3>";
echo "<table>";
echo "<tr><th>Position</th>";
echo "<th>Team</th>";
echo "<th>Points/Overall</th>";
echo "<th>Points/Last Race</th>";
echo "<th>Team Setup</th></tr>";
while($row = mysql_fetch_array($result))
{
if($row[username] == $_SESSION[username])
echo "<tr style=\"color:red;\"><td>";
else
echo "<tr><td>";
echo $counter;
echo "</td><td>";
echo $row[teamname];
echo "</td><td>";
echo $row[total_points];
echo "</td><td>";
echo "</td><td>";
echo "</td></tr>";
$counter++;
}
echo "</table>";
$query = "SELECT COUNT(members.username) AS numrows FROM members, members_leagues WHERE members.username = members_leagues.username
AND members_leagues.sub_league = '$chosenleague'";
$result = mysql_query($query) or die('Error, query failed');
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$numrows = $row['numrows'];
$maxPage = ceil($numrows/$rowsPerPage);
$self = $_SERVER['PHP_SELF'];
$nav = '';
if ($pageNum > 1)
{
$page = $pageNum - 1;
$prev = " << Prev ";
$first = " First ";
}
else
{
$prev = '';
$first = '';
}
if ($pageNum < $maxPage)
{
$page = $pageNum + 1;
$next = " Next >> ";
$last = " Last ";
}
else
{
$next = '';
$last = '';
}
echo "<div id=\"pagenum\">Page $pageNum of $maxPage ". $first . $last . $prev . $next ."</div>";
You can do it via mysql or php:
With PHP:
Found the position of the requested record in the array, then calculate the page you have to extract and execute the corresponding query. Something like.
$i = 0;
$found = false;
$team_position = 0;
while (!$found && $row = mysql_fetch_row) {
if ($row['team'] == 'team_your_searching_for') {
$team_position = $i;
$found = true;
}
$i++;
}
//calculate $top and $bottom
...
$sql = "SELECT * FROM members LIMIT $top, $bottom;";
...
With MySQL:
You can create a query that generates an autoincrement value and another that selects from the other's result. I mean
-- get the the selected member's position
SELECT team, pos FROM (SELECT team, points, #position = #position + 1 AS pos FROM members ORDER BY points) WHERE team = #the_team_your_searching_for;
-- get the nr of members
SELECT COUNT(*) FROM members;
...
-- calculate the page you wanna extract (#top, #bottom), and extract it
SELECT * FROM members LIMIT #top, #bottom;
I'm using this script to pagination. But when url does have $_GET['word'] I cant change URL's of Links. How can I do it?
<?
if (isset($_GET['page']) ) {
$pageno = $_GET['page'];
} else {
$pageno = 1;
} // if
$limit = "";
if(isset($_GET['word'])) {
$word = mysql_real_escape_string($_GET['word']);
$word = $word{0};
$limit = " WHERE baslik LIKE '$word%'";
}
$query = mysql_query("SELECT count(*) FROM m3_music_mp3" .$limit);
$query_data = mysql_fetch_row($query);
$numrows = $query_data[0];
$rows_per_page = 30;
$lastpage = ceil($numrows/$rows_per_page);
$pageno = (int)$pageno;
if ($pageno > $lastpage) {
$pageno = $lastpage;
} // if
if ($pageno < 1) {
$pageno = 1;
} // if
$limit .= " ORDER BY id DESC LIMIT " .($pageno - 1) * $rows_per_page .',' .$rows_per_page;
//$limit = 'ORDER BY id DESC LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;
$query = mysql_query("SELECT * FROM m3_music_mp3 $limit");
if ($pageno == 1) {
echo "<a>««</a> <a>«</a> ";
} else {
echo " <a href='{$_SERVER['PHP_SELF']}?sayfa=1'>««</a> ";
$prevpage = $pageno-1;
echo " <a href='{$_SERVER['PHP_SELF']}?sayfa=$prevpage'>«</a> ";
} // if
for($page_number = 1; $page_number <= $lastpage; $page_number++)
if($page_number == $pageno) {
echo "<span class='current'>$pageno</span>";
}
else {
echo "<a href='{$_SERVER['PHP_SELF']}?sayfa=$page_number' class='page' title='$page_number'>$page_number</a>";
}
if ($pageno == $lastpage) {
echo " <a>»</a> <a>»»</a> ";
} else {
$nextpage = $pageno+1;
echo " <a href='{$_SERVER['PHP_SELF']}?sayfa=$nextpage'>»</a> ";
echo " <a href='{$_SERVER['PHP_SELF']}?sayfa=$lastpage'>»»</a> ";
} // if
?>
I'm trying to do if isset $_GET['word'] set urls <a href='{$_SERVER['PHP_SELF']}?word=$word&page=$lastpage'>»»</a> if NOT <a href='{$_SERVER['PHP_SELF']}?page=$lastpage'>»»</a> i cant let it work thank you if you will help
Try following:
$word_str = "";
if(isset($_GET['word'])) {
$word_str = "&word=".$_GET['word'];
//......
}
And then just append $word_str to urls, for example
echo " <a href='{$_SERVER['PHP_SELF']}?sayfa='.$nextpage.$word_str.'>»</a> ";
You should better use $_SERVER['REQUEST_URI'] to get the current requested URI path and query. You can then use parse_url to get just the URI path and http_build_query to build the query from an array:
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
// …
$href = htmlspecialchars($_SERVER['REQUEST_URI_PATH']."?".http_build_query(array('sayfa'=>1)+$_GET), ENT_QUOTES);
echo " <a href='$href'>««</a> ";
$prevpage = $pageno-1;
$href = htmlspecialchars($_SERVER['REQUEST_URI_PATH']."?".http_build_query(array('sayfa'=>$prevpage)+$_GET), ENT_QUOTES);
echo " <a href='$href'>«</a> ";
// …