Sorting is work perfectly before I combine it with pagination. But right now I am facing with the problem this when to pass value of sorting to pagination:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?page=1 ASC LIMIT 0, 10' at line 3
Below is my code:
<?php
session_start();
$host = 'localhost';
$user = 'root';
$pass ='password';
$name = 'dbname';
$con = new mysqli ($host,$user,$pass,$name);
?>
<html>
<h2>Your Redeemed Ticket (<?php echo $_SESSION['username'];?>):</h2>
<table border='1' align='center' cellpadding='10'>
<tr align = "center">
<td>
Purchase ID
<td>
Ticket Type
<td>
Quantity
<td>
Date
</tr>
</html>
<?php
// default sorting
if(isset($_GET['sort'])){
$sortOrder = $_GET['sort'] ? :0;
/*Pagination*/
$limit = 10;
if (isset($_GET["page"]))
{
$page = $_GET["page"];
}
else
{
$page=1;
}
$start_from = ($page-1) * $limit;
$username = $_SESSION['username'];
$data =
"
SELECT *
FROM redeem
WHERE redeem_by = '$username' ORDER BY ".$sortOrder." ASC LIMIT $start_from, $limit
";
$result = $con->query($data);
if ($result === false)
die (mysqli_error($con));
while($rows = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td align='center'>";
echo $rows['purchase_id'];
echo "<td align='center'>";
echo $rows['ticket_type'];
echo "<td align='center'>";
echo $rows['qty'];
echo "<td align='center'>";
echo $rows['date'];
echo "</tr>";
}
echo "</table>";
/*PAGE NUMBER DISPLAY*/
$data2 = "SELECT COUNT(redeem_by) FROM redeem";
$rs_result = mysqli_query($con,$data2);
$row = mysqli_fetch_row($rs_result);
$total_records = $row[0];
$total_pages = ceil($total_records / $limit);
$pagLink = '';
for ($i=1; $i<=$total_pages; $i++)
{
$pagLink .="<a href='user_history.php?sort=".$sortOrder."?page=$i'>" .$i."/</a>";
};
echo "<center>".$pagLink."</center>";
/*LOGOUT*/
if(isset($_POST['logout']))
{
session_destroy();
header ("location:login.php");
exit();
}
}
?>
There are a few weird issues in your code, but the problem with your screwed up GET variable can probably be traced to here:
<a href='user_history.php?sort=".$sortOrder."?page=$i'>"
Obviously when you have url parameters, you delineate the starting point with the '?' but after that you need to seperate additional parameters with the '&'.
So it should be:
<a href='user_history.php?sort=".$sortOrder."&page=$i'>"
Related
I'm have a database with users from different countries. My pagination is working because the query counts all rows. So it gives you like 5 pages and let's say the total records are finished by page3.
My question is:
1) How can I count only records from one country let's say "australia"? And the pagination should only give me pages with results no extra pages with no results?
My code for pagination is below:
<?php
$per_page = 1;
$pages_query = mysql_query("SELECT COUNT(*) FROM `users`");
$pages = ceil(mysql_result($pages_query,0)/$per_page);
if (!isset($_GET['page']))
{
header("location: blood.php?page=1");
}
else
{
$page = $_GET['page'];
}
$start = (($page - 1)*$per_page);
$colours = mysql_query("SELECT * FROM users WHERE country ='australia' LIMIT $start,$per_page");
while($row = mysql_fetch_assoc($colours))
{
$username = $row['first_name'];
echo "$username<br>";
}
for($number=1; $number<=$pages; $number++)
{
echo ''.$number.' ';
echo" ";
}
echo "<br>Current Page: $page";
?>
how do i include the above code together with the correction suggested in the below code where results are returned after user searches for a username and lastname.
<?php
include 'core/init.php';
include 'includes/overall/oheader.php';
?>
<?php
if(isset($_POST['submit']))
{
$query = $_POST['uname_search'];
$queryl = $_POST ['lname_search'];
$min_length = 3;
if(strlen($query) >= $min_length && strlen($queryl) >= $min_length)
{
$query = htmlspecialchars($query);
$query = mysql_real_escape_string($query);
$queryl = htmlspecialchars($queryl);
$queryl = mysql_real_escape_string($queryl);
echo "<table border='1' width='250px' align='center' cellpadding='1' cellspacing='1'>";
echo "<tr align='center' bgcolor='#002C40' style='color:#FFF'>
<td height='30px' width='150px'>Username</td> <td>first_name</td> <td>last_name</td><td>email</td><td>Mobile_Number</td><td>gender</td><td>county</td><td>blood_group</td>
$raw_results =
mysql_query("SELECT * FROM `users` WHERE (`username` LIKE '%".$query."%') AND (`last_name` LIKE '%".$queryl."%')");
if(mysql_num_rows($raw_results) > 0)
{
while($results = mysql_fetch_array($raw_results))
{
$image = "images/profile/1a4671c319.jpg" ;
echo "<tr align='center' bgcolor='#002C40' style='color:#FFF'>
<td rowspan='4'>"."<img src=".$results['profile']." width=100px height=100px> "."</td>
<td >Username</td>
<td >first_name</td>
<td>last_name</td>
<td>email</td>
</tr>";
echo "<tr align='center' bgcolor='#0f7ea3'>
<td>".$results['username']."</td>
<td>".$results['first_name']."</td>
<td>".$results['last_name']."</td>
<td>".$results['email']."</td>
</tr>" ;
echo "<tr align='center' bgcolor='#002C40' style='color:#FFF'>
<td>Mobile_Number</td>
<td>gender</td>
<td>county</td>
<td>blood_group</td>
</tr>";
echo "<tr align='center' bgcolor='#0f7ea3'>
<td>".$results['Mobile_Number']."</td>
<td>".$results['gender']."</td>
<td>".$results['county']."</td>
<td>".$results['blood_group']."</td>
</tr>" ;
}
}
else{
echo "<tr align='center' bgcolor='#6C0000'>
<td colspan='8' height='25px'>No results</td><tr>";
echo "</table>";
}
}
else{
echo "Minimum length is ".$min_length;
}
}
include 'includes/overall/ofooter.php';
?>
You could apply the same where clause to the first query which counts the users:
$pages_query =
mysql_query("SELECT COUNT(*) FROM `users` WHERE country ='australia'");
# Here -----------------------------------^
I am facing a problem, and i don't know how to fix it.
If i click a link generated from this php, the results are same as displayed on 1st page. For example view.php?page=2 displays same data as view.php?page=1 or 3, etc.
That happens for 'view.php?ID=' aswell.
<?php
require_once('connection.php');
require_once('auth.php');
echo "<br /><br /><font color=red size='6'><center>Facturi emise</center></font><br /><br />";
$query = "SELECT * FROM out_fact ORDER BY ID DESC LIMIT 0, 20";
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
if (mysql_num_rows($result) > 0) {
echo "<table cellpadding=10 border=1 align=center>";
while($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td>"."<a href=javascript:window.open('view.php?ID=".$row[0]."','NAME','location=false')><font color=blue size='4'><center>".$row[1]." din data de ".$row[2]."</a></center>"."</font></td>";
echo "<td>"."<font color=red size='4'><center>".$row[3]." ".$row[12]."</center></font></td>";
echo "</tr>";
};
echo "</table>";
}
else {
echo "No rows found!";
}
echo "<tr><td> <a href='view.php?ID=".$row[0]."'>".$row[1]."</a></td></tr>";
mysql_free_result($result);
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * 20;
$sql = "SELECT COUNT(ID) FROM out_fact";
$query = mysql_query($sql);
$result = mysql_fetch_row($query);
$total_records = $result[0];
$total_pages = ceil($total_records / 20);
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='view.php?page=".$i."'>".$i."</a> ";
};
?>
How to post correct data, or what's missing. I'm new in php coding...
Thanks in advance.
Try at least using MySQLi instead of deprecated MySQL. And what you are trying to do is called Pagination.
connection.php:
<?php
$con=mysqli_connect("YourHost","YourUsername","YourPassword","YourDatabase"); /* REPLACE THE NECESSARY HOST, USERNAME, PASSWORD, AND DATABASE */
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
?>
Your main file:
<?php
include('connection.php');
require_once('auth.php');
echo "<br><br><font color=red size='6'><center>Facturi emise</center></font><br><br>";
$query = "SELECT * FROM out_fact ORDER BY ID DESC";
$result = mysqli_query($con,$query);
$count=mysqli_num_rows($result);
$r = mysqli_fetch_row($result);
$numrows = $r[0];
$rowsperpage = 10; /* NUMBER OF ROWS TO SHOW PER PAGE */
$totalpages = ceil($count / $rowsperpage);
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
$currentpage = (int) $_GET['currentpage'];
} else {
$currentpage = 1;
}
if ($currentpage > $totalpages) {
$currentpage = $totalpages;
}
if ($currentpage < 1) {
$currentpage = 1;
}
$offset = ($currentpage - 1) * $rowsperpage;
$result=mysqli_query($con,"SELECT * FROM out_fact ORDER BY ID DESC LIMIT $offset,$rowsperpage");
echo "<table cellpadding=10 border=1 align=center>";
while($row = mysqli_fetch_array($result)){
/* JUST REPLACE THE NECESSARY DATA YOU WANT TO INPUT INSIDE THIS WHILE LOOP */
$rowdata=mysqli_real_escape_string($con,$row[0]);
echo "<tr>";
echo "<td><a href='view.php?ID=$rowdata&location=false' target='_blank'><font color=blue size='4'><center>".$row[1]." din data de ".$row[2]."</a></center>"."</font></td>"; /* JUST REPLACE THE NECESSARY DATA IN THE LINK IF YOU MUST */
echo "<td>"."<font color=red size='4'><center>".$row[3]." ".$row[12]."</center></font></td>";
echo "</tr>";
} /* END OF WHILE LOOP */
if($count==0){
echo "<tr><td></td><td>No results found.</td><td></td></tr>";
}
else { /* START OF PAGINATION LINK */
echo '<tr height="30px;" valign="bottom"><td></td><td>';
echo "<table style='border-collapse:separate; border-spacing:3px;'><tr>";
/****** build the pagination links ******/
$range = 2;
if ($currentpage > 1) {
$prevpage = $currentpage - 1;
echo "<td style='width:70px; background-color:fff; border:solid #08c 1px; font-size:14px;' align='center'> <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage' style='background-color:fff;'>Previous</a> </td>";
}
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
if (($x > 0) && ($x <= $totalpages)) {
if ($x == $currentpage) {
echo "<td style='width:20px; background-color:fff; font-size:14px; border:solid #ccc 2px;' align='center'> <font color='#ccc'><b>$x</b></font> </td>";
} else {
echo "<td style='width:20px; background-color:fff; font-size:14px; border:solid #08c 1px;' align='center'> <a href='{$_SERVER['PHP_SELF']}?currentpage=$x' style='background-color:fff;'>$x</a> </td>";
}
}
}
if ($currentpage != $totalpages) {
$nextpage = $currentpage + 1;
echo "<td style='width:70px; background-color:fff; font-size:14px; border:solid #08c 1px;' align='center'> <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage' style='background-color:fff;'>Next</a> </td>";
} // end if
/****** end build pagination links ******/
echo "</tr></table></td></tr>";
} /* END OF ELSE IF COUNT 0 */
echo '</table>';
?>
I was following a tutorial on basic php tables to show the users with pagination:
http://www.killersites.com/community/index.php?/topic/1969-basic-php-system-vieweditdeleteadd-records/
the problem that i have is my platform does not support MySQL so i change it to MySQLi
the second problem is that the it should display only one user per page but it just show all of them in 1 page and when click on for example on page 2 it is show me error page
this is an image to better description :
http://store2.up-00.com/2014-02/1391920754996.jpg
and this is the code that i am using :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
</head>
<body>
<?php
/*
VIEW-PAGINATED.PHP
Displays all data from 'players' table
This is a modified version of view.php that includes pagination
*/
// connect to the database
include('config.php');
// number of results to show per page
$per_page = 1;
// figure out the total pages in the database
$result = mysqli_query($connecDB,"SELECT * FROM users");
$total_results = mysqli_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 pagination
echo "<p> | <b>View Page:</b> ";
for ($i = 1; $i <= $total_pages; $i++)
{
echo "<a href='admin_user_list.php?page=$i'>$i</a> ";
}
echo "</p>";
// display data in table
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>First Name</th> <th>Last Name</th>";
// loop through results of database query, displaying them in the table
for ($i = $start; $i < $end; $i++)
{
// 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>";
while($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$fname = $row['first_name'];
$lname = $row['last_name'];
echo "<tr><td>";
echo $id;
echo "</td>";
echo "<td>";
echo $fname;
echo "<td>";
echo $lname;
echo "</td></tr>";
}
echo "</td></tr>";
}
// close table>
echo "</table>";
// pagination
?>
<p>Add a new record</p>
</body>
</html>
I couldn't fix your existing script, so I found a pagination script that I modified and has worked for me.
You will undoubtingly want to modify it, but it works.
Just change the DB credentials and other things you will find throughout the script.
There are a few comments in it also on commented-out options.
<?php
$DB_HOST = "xxx";
$DB_NAME = "xxx";
$DB_PASS = "xxx";
$DB_USER = "xxx";
$db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($db->connect_errno > 0) {
die('Connection failed [' . $db->connect_error . ']');
}
$sql2 = "SELECT COUNT(id) FROM users ";
$query2 = mysqli_query($db, $sql2);
$row = mysqli_fetch_row($query2);
// Here we have the total row count
$rows = $row[0];
// This is the number of results we want displayed per page
$page_rows = 1;
// This tells us the page number of our last page
$last = ceil($rows/$page_rows);
// This makes sure $last cannot be less than 1
if($last < 1){
$last = 1;
}
// Establish the $pagenum variable
$pagenum = 1; // do not change this
// Get pagenum from URL vars if it is present, else it is = 1
if(isset($_GET['pn'])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
// This makes sure the page number isn't below 1, or more than our $last page
if ($pagenum < 1) {
$pagenum = 1;
} else if ($pagenum > $last) {
$pagenum = $last;
}
// This sets the range of rows to query for the chosen $pagenum
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
// This is your query again, it is for grabbing just one page worth of rows by applying $limit
$sql = "SELECT id, first_name, last_name FROM users ORDER BY id ASC $limit";
$query = mysqli_query($db, $sql);
// This shows the user what page they are on, and the total number of pages
$textline1 = "Names (<b>$rows</b>)";
$textline2 = "Page <b>$pagenum</b> of <b>$last</b>";
// Establish the $paginationCtrls variable
$paginationCtrls = '';
// If there is more than 1 page worth of results
if($last != 1){
/* First we check if we are on page one. If we are then we don't need a link to
the previous page or the first page so we do nothing. If we aren't then we
generate links to the first page, and to the previous page. */
if ($pagenum > 1) {
$previous = $pagenum - 1;
$paginationCtrls .= 'Previous ';
// Render clickable number links that should appear on the left of the target page number
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i > 0){
$paginationCtrls .= ''.$i.' ';
}
}
}
// Render the target page number, but without it being a link
$paginationCtrls .= ''.$pagenum.' ';
// Render clickable number links that should appear on the right of the target page number
for($i = $pagenum+1; $i <= $last; $i++){
$paginationCtrls .= ''.$i.' ';
if($i >= $pagenum+4){
break;
}
}
// This does the same as above, only checking if we are on the last page, and then generating the "Next"
if ($pagenum != $last) {
$next = $pagenum + 1;
$paginationCtrls .= ' Next ';
}
}
$dynamicList = '';
// display data in table
echo "<table border='1' cellpadding='10'>";
// echo "<tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th></th> <th></th></tr>";
echo "<tr> <th>ID</th> <th>First Name</th> <th>Last Name</th>";
echo "<tr>";
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
/*
$id = $row["id"];
$product_name = $row["first_name"];
$price = $row["last_name"];
*/
$id = $row['id'];
$fname = $row['first_name'];
$lname = $row['last_name'];
echo "<tr><td>";
echo $id;
echo "</td>";
echo "<td>";
echo $fname;
echo "<td>";
echo $lname;
echo "</td></tr>";
// you can use and modify this below
// the <!-- and --> tags can be taken out. Those are regular HTML comment tags.
$dynamicList .= "
<!--
<li><div class='product'>
<a href='pager.php?id=$id' class='info'>
<span class='holder'>
<img src='images/$id.jpg' alt='$product_name' />
<span class='book-name'>$product_name</span>
</a>
<a href='pager.php?id=$id' class='buy-btn'> (link) <span class='price'>$price</span></a>
</div>
</li>
-->
";
}
// Close your database connection
mysqli_close($db);
?>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body{ font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;}
div#pagination_controls{font-size:21px;}
div#pagination_controls > a{ color:#06F; }
div#pagination_controls > a:visited{ color:#06F; }
</style>
</head>
<body>
<div>
<h2><?php echo $textline1; ?> Paged</h2>
<p><?php echo $textline2; ?></p>
<p><?php echo $dynamicList; ?></p>
<div id="pagination_controls"><?php echo $paginationCtrls; ?></div>
</div>
</body>
</html>
this code showing all MySQL table data to any users but i want only admin and user to show data of mysql query
i have multiple users
1.admin
2.user123
3.xyz
so i want only admin and user to show MySQL table data how can i do this
example
if admin and user123 open the page then mysql data showing correct if xyz user open the page then it will not showing any data
user login name <?php echo $_SESSION['SESS_FIRST_NAME']; ?>
i want to add this one in to mysql query to showing result only admin and user
$query = "SELECT * FROM `follower` WHERE `followername` LIKE '".$letter."%' ORDER BY `followername` ASC LIMIT $from, $max_results";
complete code
<?php
$max_results = 10;
$from = (($page * $max_results) - $max_results);
if(empty($_POST)) {
$query = "SELECT * FROM `follower` WHERE `followername` LIKE '".$letter."%' ORDER BY `followername` ASC LIMIT $from, $max_results";
}
$result = mysql_query("SET NAMES utf8"); //the main trick
$result = mysql_query($query) or die(mysql_error());
$rows = mysql_num_rows($result);
echo "<table class='gridtable' border='1' cellpadding='0' cellspacing='0'>";
echo "<tr><th>Name</th><th>Company Name</th><th>Mobile No</th></tr>";
if ($rows > 0) {
while($row = mysql_fetch_array($result)) {
echo "<tr><td>";
echo $row['followername'];
echo "</td><td>";
echo $row['companyname'];
echo "</td><td>";
echo $row['mobileno'];
echo "</td><td>";
echo $row['contractdatee'];
echo "</td></tr>";
}
} else {
echo "<tr><td align=\"center\" colspan=\"4\">No results found!</td></tr>";
}
echo "</table>";
// Figure out the total number of results in DB:
$total_results = mysql_result(mysql_query("SELECT COUNT(*) as followername FROM follower ORDER BY followername ASC"),0);
// Figure out the total number of pages. Always round up using ceil()
$total_pages = ceil($total_results / $max_results);
// Build Page Number Hyperlinks
echo "<p class=\"style2\">Pages: ";
// Build Previous Link
if($page > 1){
$prev = ($page - 1);
echo "Previous ";
}
for($i = 1; $i <= $total_pages; $i++){
if(($page) == $i){
echo "$i ";
} else {
echo " ";
}
}
// Build Next Link
if($page < $total_pages){
$next = ($page + 1);
echo "Next";
}
echo "</p>";
mysql_close();
?>
this is showing all floors of building and i want to show selected building floors how can i do this i use this link floors.php?id=Building1 but its is not working please help me
if i write in there building1 it is working fine where buildingname='building1'
if i use this one where buildingname='$id' it is not working
how can i use like this
floors.php?id=Building1
if i enter this link then it will show all selected building result
<?php
$max_results = 8;
$from = (($page * $max_results) - $max_results);
if(empty($_POST)) {
$query = "SELECT * FROM floors where buildingname='$id' ORDER BY floorno ASC LIMIT $from, $max_results ";
}
$result = mysql_query("SET NAMES utf8"); //the main trick
$result = mysql_query($query) or die(mysql_error());
$rows = mysql_num_rows($result);
$count=0;
while($row = mysql_fetch_array($result))
{
if($count%4==0)
{
echo "<tr/>";
echo "<tr>";
}
echo "<td><div align='center'><img src='images/floor.gif' width='60' height='90'></a><p>" . $row['floorno'] . "</p><div></td>";
$count++;
}
echo "</tr>";
echo "</table>";
echo '</div>';
?>
if(empty($_POST)) {
$query = "SELECT * FROM floors where buildingname='$id' ORDER BY floorno ASC LIMIT $from, $max_results ";
}
the right is:
if (isset($_GET['id'])) {
$id = filter_input(INPUT_GET, 'id');
$query = "SELECT * FROM floors where buildingname='$id' ORDER BY floorno ASC LIMIT $from, $max_results ";
}
that may help you.
<?php
$id =isset($_GET['id'])?$_GET['id']:null; // here you put value in $id only if it has some value.
$max_results = 8;
$from = (($page * $max_results) - $max_results);
if($id != null) {
$query = sprintf("SELECT * FROM floors WHERE buildingname='%s' ORDER BY floorno ASC LIMIT $from, $max_results", mysql_real_escape_string($id)); // safe from sql injection
$result = mysql_query("SET NAMES utf8"); //the main trick
$result = mysql_query($query) or die(mysql_error());
$rows = mysql_num_rows($result);
$count=0;
while($row = mysql_fetch_array($result))
{
if($count%4==0)
{
echo "<tr/>";
echo "<tr>";
}
echo "<td><div align='center'><img src='images/floor.gif' width='60' height='90'></a><p>" . $row['floorno'] . "</p><div></td>";
$count++;
}
}
echo "</tr>";
echo "</table>";
echo '</div>';
?>