Migration from MySQL to MySQLi extension - php

I have a script written in Mysql that just lists people's names. It works fine in mysql but i have been trying to get it to update to mysqli and i got most of it. However, the results are supposed to be paginated. The pagination works fine because there should be 5 pages and thats where it stops....but ALL of the results just show up on every page. Not sure what i am doing...any help would be greatly appreciated....I know it has to do with "mysql_result"
Here is my new code in mysqli:
<?php
include ('paginate.php'); //include of paginat page
$per_page = 10; // number of results to show per page
$result = $con->query("SELECT EmployeeID,FirstName,LastName FROM employee;");
//If Database Error...Print the error and exit
if (!$result) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
//If No Database Error.....Continue
if ($result)
{
// Return the number of rows in result set
$total_results=mysqli_num_rows($result);
//printf("Result set has %d rows.\n",$total_results);
// Free result set
}
//total pages we going to have
$total_pages = ceil($total_results / $per_page);
//if page is setcheck
$show_page='';
if (isset($_GET['page'])) {
$show_page = $_GET['page'];//it will telles the current page
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
$page = intval(isset($_GET['page']));
$tpages=$total_pages;
if ($page <= 0)
$page = 1;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>View All Employees</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
<div class="container">
<div class="row">
<div class="logo">
<img src="../admin/images/logo-thompson-industrial-services.gif" class="text- center"width="259" height="59" />
</div>
</div>
<br />
<div class="row">
<div class="span6 offset3">
<div class="mini-layout">
<?php
$reload = $_SERVER['PHP_SELF'] . "?tpages=" . $tpages;
echo '<div class="pagination"><ul>';
if ($total_pages > 1) {
echo paginate($reload, $show_page, $total_pages);
}
echo "</ul></div>";
// display data in table
echo "<table class='table table-bordered'>";
echo "<thead><tr><th>First Name</th> <th>Last Name</th></tr></thead>";
// loop through results of database query, displaying them in the table
// 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;
}
while($row = mysqli_fetch_assoc($result)) {
$id = $row['EmployeeID'];
$fname = $row['FirstName'];
$lname = $row['LastName'];
echo "<tr>";
echo '<td class="col-md-4">' .$fname .'</td>';
echo '<td class="col-md-4">' .$lname .'</td>';
echo "</tr>";
}
}
// close table>
echo "</table>";
?>
</div>
</div>
</div>
</div>
</body>
</html>
And here is my original code in mysql:
<?php
error_reporting(E_ALL | E_NOTICE);
ini_set('display_errors', '1');
error_reporting(E_ALL ^ E_DEPRECATED);
include('config.php'); //include of db config file
include ('paginate.php'); //include of paginat page
$per_page = 10; // number of results to show per page
$result = mysql_query("SELECT * FROM employee");
$total_results = mysql_num_rows($result);
$total_pages = ceil($total_results / $per_page);//total pages we going to have
//-------------if page is setcheck------------------//
$show_page='';
if (isset($_GET['page'])) {
$show_page = $_GET['page']; //it will telles the current page
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
$page = intval(isset($_GET['page']));
$tpages=$total_pages;
if ($page <= 0)
$page = 1;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>View Employees</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<style type="text/css">
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="logo">
<img src="../admin/images/logo-thompson-industrial-services.gif" class="text-center"width="259" height="59" />
</div>
</div>
<br />
<div class="row">
<div class="span6 offset3">
<div class="mini-layout">
<?php
$reload = $_SERVER['PHP_SELF'] . "?tpages=" . $tpages;
echo '<div class="pagination"><ul>';
if ($total_pages > 1) {
echo paginate($reload, $show_page, $total_pages);
}
echo "</ul></div>";
// display data in table
echo "<table class='table table-bordered'>";
echo "<thead><tr><th>First Name</th> <th>Last Name</th></tr></thead>";
// 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>";
echo '<td>' . mysql_result($result, $i, 'FirstName') . '</td>';
echo '<td>' . mysql_result($result, $i, 'LastName') . '</td>';
echo "</tr>";
}
// close table>
echo "</table>";
// pagination
?>
</div>
</div>
</div>
</div>
</body>
</html>
I am doing something wrong here and i cant figure it out....
Any help would be greatly appreciated...
Thanks a lot.

I would also just remove the while statement and use mysqli_data_seek in conjunction with mysqli_fetch_accoc. The MySQLi_data_seek points to the result I need. Check it out:
// display data in table
echo "<table class='table table-bordered'>";
echo "<thead><tr><th>First
Name</th> <th>Last Name</th></tr></thead>";
// loop through results of database query, displaying them in the table
// 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;
}
//go to the column you want the results
mysqli_data_seek($result, $i);
$row = mysqli_fetch_assoc($result);
// echo out the contents of the row into a table
echo "<tr>";
echo '<td>' . $row['FirstName'] . '</td>';
echo '<td>' . $row['LastName'] . '</td>';
echo "</tr>";
}
}
echo "</table>";

The way you are extracting the query is the problem. Once you enter the while statement it does not leave until all the results are done and then it executes
if ($i == $total_results) {
break;
}
So it never gets a chance to end at $i greater than $total_result. The fix is to include LIMIT and OFFSET in the query. That means you have to fix the pagination page too.
So just run the query again like:
// display data in table
echo "<table class='table table-bordered'>";
echo "<thead><tr><th>First
Name</th> <th>Last Name</th></tr></thead>";
// loop through results of database query, displaying them in the table
// loop through results of database query, displaying them in the table
for ($i = $start; $i < $end; $i++) {
// run the query again
$sql ="SELECT EmployeeID,FirstName,LastName FROM employee LIMIT $per_page OFFSET $end;
$result = $con->query($sql);
while($row = mysqli_fetch_assoc($result)) {
$id = $row['EmployeeID'];
$fname = $row['FirstName'];
$lname = $row['LastName'];
echo "<tr>";
echo '<td class="col-md-4">' .$fname .'</td>';
echo '<td class="col-md-4">' .$lname .'</td>';
echo "</tr>";
}
}
echo "</table>";

Related

Adding a counter to the table

I'm trying to add a counter to the table in the following code. but I couldn't be successful. Can I get a little help, please? thanks. Something like this:
$counter = 0;
$counter++;
if($counter % 33 == 0)
So that when the counter is added, table will continue after %33 on the right of the page, and it will continue like that, instead of going down the page.
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="etc/sumain.css" />
</head>
<body>
<table class="tbresult">
<?php
include ("confige.php");
$query = 'select * from employees';
$result = mysqli_query($link, $query);
if (!$result) {
$message = 'ERROR:' . mysqli_error($link);
return $message;
} else {
$i = 0;
echo '<form name="select" action="" method="GET">';
echo '<select name="mySelect" id="mySelect" onchange="this.form.submit()">';
while ($i < mysqli_field_count($link)) {
$meta =
mysqli_fetch_field_direct($result, $i);
echo '<option>' . $meta->name . '</option>';
$i = $i + 1;
}
echo '</select>';
echo '</form>';
}
if(isset($_GET['mySelect'])) {
$myselect = $_GET['mySelect'];
$sql = "SELECT `$myselect` as mySelect FROM employees"; // add column alias
$result = mysqli_query($link, $sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc())
{
echo "<tr><td>" . $row["mySelect"] . "</td></tr>";
}
echo "</table>";
}
}
mysqli_close($link);
?>
</body>
</html>
First, don't have an HTML form inside a table, this is not valid, AFIK, and can cause you many troubles in different browsers.
You need simply open the table once, then create a counter = 0 and on each while loop add 1 to it. Then check, if it divides by 33 than you close the table and open a new one. After the loop you close the last table.
The side by side alignment can be done with CSS, something like .tbresult {float: left; width: 200px;}
Something like this:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="etc/sumain.css" />
</head>
<body>
<?php
include ("confige.php");
$query = 'select * from employees';
$result = mysqli_query($link, $query);
if (!$result) {
$message = 'ERROR:' . mysqli_error($link);
return $message;
} else {
$i = 0;
echo '<form name="select" action="" method="GET">';
echo '<select name="mySelect" id="mySelect" onchange="this.form.submit()">';
while ($i < mysqli_field_count($link)) {
$meta =
mysqli_fetch_field_direct($result, $i);
echo '<option>' . $meta->name . '</option>';
$i = $i + 1;
}
echo '</select>';
echo '</form>';
}
if(isset($_GET['mySelect'])) {
$myselect = $_GET['mySelect'];
$sql = "SELECT `$myselect` as mySelect FROM employees"; // add column alias
$result = mysqli_query($link, $sql);
if ($result->num_rows > 0) {
// output data of each row
$table_row_counter = 0;
echo '<table class="tbresult">';
while($row = $result->fetch_assoc())
{
$table_row_counter++;
if ($table_row_counter % 33 == 0) {
echo '</table>';
echo '<table class="tbresult">';
}
echo "<tr><td>" . $row["mySelect"] . "</td></tr>";
}
}
}
mysqli_close($link);
?>
</body>
</html>

Pagination links disappear when clicked on the next or any other page

I'm having a problem with PHP pagination.
When I click on the next page to see next results, pagination links and data just disappear.
I tried various Pagination classes, but decided to stop on this solution.
Will be extremely grateful if someone helps to find a fix.
<html>
<head>
<title></title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<?Php
require "config_pag.php";
$field = $_POST['field'];
$state = $_POST['state'];
$page_name="search.php";
$start=$_GET['start'];
if(strlen($start) > 0 and !is_numeric($start)){
echo "Data Error";
exit;
}
$eu = ($start - 0);
$limit = 2;
$this1 = $eu + $limit;
$back = $eu - $limit;
$next = $eu + $limit;
$nume = $dbo->query("select count(id) from posts WHERE state = '$state' AND field = '$field'")->fetchColumn();
echo "<TABLE class='t1'>";
echo "<tr><th>ID</th><th>State</th><th>Fields</th><th>Description</th></tr>";
$query=" SELECT * FROM posts WHERE state = '$state' AND field = '$field' limit $eu, $limit ";
foreach ($dbo->query($query) as $row) {
$m=$i%2;
$i=$i+1;
echo "<tr class='r$m'><td>".$row['id']."</td><td>".$row['state']."</td><td>".$row['field']."</td><td>".$row['description']."</td></tr>";
}
echo "</table>";
if($nume > $limit ){
echo "<table align = 'center' width='50%'><tr><td align='left' width='30%'>";
if($back >=0) {
print "<a href='$page_name?start=$back'><font face='Verdana' size='2'>PREV</font></a>";
}
echo "</td><td align=center width='30%'>";
$i=0;
$l=1;
for($i=0;$i < $nume;$i=$i+$limit){
if($i <> $eu){
echo " <a href='$page_name?start=$i'><font face='Verdana' size='2'>$l</font></a> ";
}
else { echo "<font face='Verdana' size='4' color=red>$l</font>";}
$l=$l+1;
}
echo "</td><td align='right' width='30%'>";
if($this1 < $nume) {
print "<a href='$page_name?start=$next'><font face='Verdana' size='2'>NEXT</font></a>";}
echo "</td></tr></table>";
}
?>
</html>

search and pagination not work

hello I try to combine the two scripts from the book PHP 6 and MySQL 5 for Dynamic Web Sites. I did search and pagination, but when I go to the next page - did not work.
I posted two screenshots below.
if someone could show me how I make a mistake I will be grateful.
<?php require_once("../../includes/functions_2.php"); ?>
<?php
//database connect
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "1qazxsw2";
$dbname = "dw_bookstore";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
//sprawdzenie polaczenia
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//zmaiana znako na utf8
if (!mysqli_set_charset($connection, "utf8")) {
printf("Error loading character set utf8: %s\n", mysqli_error($connection));
} else {
//printf("Kodowanie ustawione na: %s\n", mysqli_character_set_name($connection));
}
?>
<?php
// Number of records to show per page:
$display = 3;
// Determine how many pages there are...
if (isset($_GET['p']) && is_numeric($_GET['p'])) { // Already been determined.
$pages = $_GET['p'];
} else { // Need to determine.
#$query = $_GET['query'];
$query4 = "SELECT COUNT(id) ";
$query4 .= "FROM photographs ";
$query4 .= "WHERE `nazwa` LIKE '%".$query."%' ";
//$query .= "WHERE visible = 1 ";
$result = #mysqli_query ($connection, $query4);
$row = #mysqli_fetch_array ($result, MYSQLI_NUM);
$records = $row[0];
// Count the number of records:
if ($records > $display) { // More than 1 page.
$pages = ceil ($records/$display);
} else {
$pages = 1;
}
} // End of p IF.
// Determine where in the database to start returning results...
if (isset($_GET['s']) && is_numeric($_GET['s'])) {
$start = $_GET['s'];
} else {
$start = 0;
}
// Make the query:
#$query = $_GET['query'];
$query3 = "SELECT * ";
$query3 .= "FROM photographs ";
$query3 .= "WHERE `nazwa` LIKE '%".$query."%' ";
$query3 .= "OR `kod` LIKE '%".$query."%' ";
//$query .= "AND visible = 1 ";
$query3 .= "ORDER BY id ASC LIMIT $start, $display ";
$result3 = mysqli_query ($connection, $query3);
?>
<?php
// 2. Perform database query
$query2 = "SELECT * ";
$query2 .= "FROM photographs ";
//$query2 .= "WHERE visible = 1 ";
$query2 .= "ORDER BY nazwa ASC ";
$result2 = mysqli_query($connection, $query2);
// Test if there was a query error
if (!$result2) {
die("Database query failed.");
}
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>List_n01</title>
<link href="../../stylesheets/main_2.css" rel="stylesheet" type="text/css" media="screen, projection" />
</head>
<body>
<div id="wrapper">
<div id="header">
<h2>Cennik: Panel Administracyjny</h2>
</div>
<div id="mainContent">
<h1>Graphic Design</h1>
<?php
// Count the number of returned rows:
$num = mysqli_num_rows($result2);
if ($num > 0) { // If it ran OK, display the records.
// Print how many rows there are:
echo "<p>W bazie znajduje się $num pozycji.</p>\n"; ?>
<form action="<?php echo $_SERVER ['PHP_SELF']; ?>" method="GET">
<fieldset>
<ul class="formList">
<li>
<input type="text" name="query" placeholder="Szukana fraza... " />
<input type="submit" value="Search" />
</li>
</fieldset>
</form>
<table id="article">
<caption></caption>
<colgroup>
</colgroup>
<tr>
<th>Zdjęcie:</th>
<th>Typ:</th>
<th>Wielkość:</th>
<th>Nazwa:Nazwa:</th>
<th>Kod:</th>
<th>Edytuj:</th>
<th>Szczegóły:</th>
<th>Usuń:</th>
</tr>
<?php
// 3. Use returned data (if any)
while($row = mysqli_fetch_assoc($result3)) {
// output data from each row
?>
<tr>
<td><img src="../images/<?php echo $row['filename']; ?>" width="150" class="article" /></td>
<td><?php echo $row['type']; ?></td>
<td><?php echo size_as_kb($row['size']); ?></td>
<td><?php echo $row['nazwa']; ?></td>
<td><?php echo $row['kod']; ?></td>
<td>Edytuj</td>
<td>Detale</td>
<td>{Usuń}</td>
</tr>
<?php
}
?>
</table>
<?php
// 4. Release returned data
mysqli_free_result($result3);
} else { // If no records were returned.
echo '<p class="error">There are currently no rows.</p>';
}
?>
<?php
// Make the links to other pages, if necessary.
if ($pages > 1) {
echo '<br /><p>';
$current_page = ($start/$display) + 1;
// If it's not the first page, make a Previous button:
if ($current_page != 1) {
echo 'Previous ';
}
// Make all the numbered pages:
for ($i = 1; $i <= $pages; $i++) {
if ($i != $current_page) {
$distance = $current_page - $i;
if (abs($distance) < 5){
echo '' . $i . ' ';
}
} else {
echo $i . ' ';
}
} // End of FOR loop
// If it's not the last page, make a Next button:
if ($current_page != $pages) {
echo 'Next';
}
echo '</p>'; // Close the paragraph.
} // End of links section.
?>
</div>
<div id="footer">
<p>Copyright <?php echo date("Y", time()); ?>, Cleoni</p></div>
</div>
</body>
</html>
<?php
// 5. Close database connection
mysqli_close($connection);
?>
you are facing issues because in your second url, the query parameter is missing, you should have also have the query=car parameter in get as the data that is been searched is searched with that parameter according to the script...
Change code from around line 184-204 to the following
// If it's not the first page, make a Previous button:
if ($current_page != 1) {
echo 'Previous ';
}
// Make all the numbered pages:
for ($i = 1; $i <= $pages; $i++) {
if ($i != $current_page) {
$distance = $current_page - $i;
if (abs($distance) < 5){
echo '' . $i . ' ';
}
} else {
echo $i . ' ';
}
} // End of FOR loop
// If it's not the last page, make a Next button:
if ($current_page != $pages) {
echo 'Next';
}

Show contents of categories, php dynamical tables

I am trying to print the contents of items by their category in a web page in this manner:
Category1:
Item1 item2 item3
item4 item5...
Category2
item1 item2 ...
This my PHP code:
$cat="";
$maxcols = 3;
$i = 0;
while ($row = $result->fetch_assoc()) {
if ($i == $maxcols) {
$i = 0;
echo "</tr><tr>";
}
if($row['name']!=$cat)
{
echo "<table>
<tr><td collspan='3'>".$row['name']."</td></tr>
<tr>";
}
echo "<td>".$row['title']."</td>";
$cat=$row['name'];
$i++;
}
while ($i <= $maxcols) {
echo "<td> </td>";
$i++;
echo "</table>";
}
What I am getting is:
<table>
<tr><td collspan='3'>Archivers</td></tr>
<tr><td>7-Zip</td><td>IZArc</td><td>dfssdfsdf sdfsdf</td></tr><tr><td>fgdgdfgd</td><td>sdfsdfsdfsdf dsfsdfsd</td><table>
<tr><td collspan='3'>Benchmark</td></tr>
<tr><td>Fresh Diagnose</td><td> </td></table>
What I want to get is:
<table>
<tr><td collspan='3'>Archivers</td></tr>
<tr><td>7-Zip</td><td>IZArc</td><td>dfssdfsdf sdfsdf</td></tr>
<tr><td>fgdgdfgd</td><td>sdfsdfsdfsdf dsfsdfsd</td>**<td> </td></tr>
</table>**
<table>
<tr><td collspan='3'>Benchmark</td></tr>
<tr><td>Fresh Diagnose</td><td> </td><td> </td>
</table>
First of all, you have very 'messy' code. I suppose you need some more code to add the part between the stars, but I think you should use a cleaner approach.
I suppose you are using mysql, which supports the GROUP_CONCAT()-function. It would be wise to use that in this case.
Make a query:
SELECT name, GROUP_CONCAT( title SEPERATOR '|') as titles FROM your_database GROUP BY name
The results per category are now in one row.
//Amount of rows
$maxcols = 3;
while( $row = $result->fetch_assoc() ) {
//The seperator needs to be something that isn't in the values it seperates
//This creates an array with the titles for this category
$titles = explode( '|', $row['titles'] );
echo '
<table>
<tr>
<td colspan="' .$maxcols. '">' .$row['name']. '</td>
</tr>';
//$offset + $i is the position in the array of titles
$offset = 0;
//This loop ensures each row is properly opened and closed
while( $offset < count( $titles ) ) {
echo '<tr>';
//This will ensure each row has $maxcols td's in it
for( $i = 0; $i < $maxcols; $i++ ) {
if( isset( $titles[ $offset + $i ] ) ) {
echo '<td>' .$titles[ $offset + $i ]. '</td>';
} else {
echo '<td> </td>';
}
}
$offset += $maxcols;
echo '</tr>';
}
echo '</table>';
}
Thank you very much, Sumurai8! Your idea works great. Here is my php code:
<?php
include_once('include/db.inc.php');
$sql="SELECT m.name, GROUP_CONCAT(s.title order by s.title SEPARATOR '|' ) as titles FROM menu m, software s where m.id=s.category
GROUP BY m.name
order by m.name";
$result = $mysqli->query($sql);
$cat="";
$maxcols = 3;
//$i = 0;
echo "
<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>
<html>
<head>
<title>content</title>
<meta content='text/html; charset=utf-8' http-equiv='content-type'>
<meta content='Software Details' name='description'>
<link href='styles/fontstyle.css' rel='stylesheet' type='text/css'>
<link href='styles/style.css' rel='stylesheet' type='text/css'>
</head>
<body class='body'>";
while( $row = $result->fetch_assoc() ) {
//The seperator needs to be something that isn't in the values it seperates
//This creates an array with the titles for this category
$titles = explode( '|', $row['titles'] );
echo "
<table>
<tr><td colspan='" .$maxcols. "'>" .$row['name']. "</td></tr> \n";
//$offset + $i is the position in the array of titles
$offset = 0;
//This loop ensures each row is properly opened and closed
while( $offset < count( $titles ) ) {
echo "<tr>";
//This will ensure each row has $maxcols td's in it
for( $i = 0; $i < $maxcols; $i++ ) {
if( isset( $titles[ $offset + $i ] ) ) {
echo "<td>" .$titles[ $offset + $i ]. "</td>";
} else {
echo "<td> </td>";
}
}
$offset += $maxcols;
echo "</tr> \n";
}
echo "</table><br> \n";
}
This is the output, just the way I want it:
<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>
<html>
<head>
<title>content</title>
<meta content='text/html; charset=utf-8' http-equiv='content-type'>
<meta content='Software Details' name='description'>
<link href='styles/fontstyle.css' rel='stylesheet' type='text/css'>
<link href='styles/style.css' rel='stylesheet' type='text/css'>
</head>
<body class='body'>
<table>
<tr><td colspan='3'>Archivers</td></tr>
<tr><td>7-Zip</td><td>IZArc</td><td>dfssdfsdf sdfsdf</td></tr>
<tr><td>fgdgdfgd</td><td>sdfsdfsdfsdf dsfsdf</td><td> </td></tr>
</table><br>
<table>
<tr><td colspan='3'>Benchmark</td></tr>
<tr><td>Fresh Diagnose</td><td> </td><td> </td></tr>
</table><br>
</body>
</html>

Using PHP to search a MySQL database and return paged results

I've come across a problem but any help would be appreciated.
When I query the database using the results posted from a form, the pagination works initially i.e. for the first 10 records but when I click on the 2 hyperlink of the pagination for the second page of results it loses the $_POST variable and returns to the full data set.
What is the best way of keeping these variables available for the second (and further) pages?
The below is my complete php file.
<html>
<head>
<link rel="stylesheet" type="text/css"
href="design.css">
</head>
<body>
<?php
include("header.php");
?>
<center>
<div id="content" class="frm">
<a href='admin.php' style='float:left'>Back!</a>
<h2>Search Result</h2>
<br><br>
<?php
include("../config.inc");
$find=$_GET['find'];
// get page no and set it to page variable, if no page is selected so asign first page bydefualt
if (isset($_GET["page"])){
$page = $_GET["page"];
}
else {
$page=1;
}
// count all record in this table then divide it on 10 in order to find the last page----- every page has 10 record display
$sql = "SELECT COUNT(*) FROM tt where TTT='$find' ";
$rs_result = mysql_query($sql);
$row = mysql_fetch_row($rs_result);
$total_records = $row[0];
$total_pages = ceil($total_records / 2);
// this line check that page no must be in integer format
$page = (int)$page;
if ($page > $total_pages) {
$page = $total_pages;
} // if
if ($page < 1) {
$page= 1;
} // if
$start_from = ($page-1) * 2;
$q=mysql_query("select * from tt where TTT='$find' order by ID limit $start_from,2");
$c=mysql_query("select count(*) from tt where TTT='$find'");
echo "<center>".mysql_result($c,0)."Filtered</center>";
echo "<center>";
echo "<table border='2' bgcolor=#CCCCCC>
<tr>
<th>TTT</th>
<th>Enroll Date</th>
<th>Gradution Date</th>
<th>ID</th>
</tr>";
while($row=mysql_fetch_array($q))
{
echo "<tr>";
echo "<td>".$row['TTT']."</td>";
echo "<td>".$row['Enroll_Date']."</td>";
echo "<td>".$row['Graduation_Date']."</td>";
echo "<td>".$row['ID']."</td>";
}
echo "</table>";
echo "<center>";
// paginatio start here
if ($page== 1) {
echo " << < ";
} else {
echo " <a href='{$_SERVER['PHP_SELF']}?page=1'><<</a> ";
$prevpage = $page-1;
echo " <a href='{$_SERVER['PHP_SELF']}?page=$prevpage'><</a> ";
} // if
echo " ( Page [$page] of [$total_pages] ) ";
if ($page == $total_pages) {
echo " > >> ";
} else {
$nextpage = $page+1;
echo " <a href='{$_SERVER['PHP_SELF']}?page=$nextpage'>></a> ";
$lastpage=$total_pages;
echo " <a href='{$_SERVER['PHP_SELF']}?page=$lastpage'>>></a> ";
} // if
?>
</div>
</center>
<?php
include("footer.php");
?>
</body>
</html>
You have to pass the filtering criteria along with links to next pages.
echo " <a href='{$_SERVER['PHP_SELF']}?page=1&find=$find'><<</a> ";
and so on with every other link.

Categories