I have this code that displays the records in the receipt page.
<?Php
require "config.php";
$page_name="currentout.php";
$start=$_GET['start'];
if(strlen($start) > 0 and !is_numeric($start)){
echo "Data Error";
exit;
}
$eu = ($start - 0);
$limit = 10;
$this1 = $eu + $limit;
$back = $eu - $limit;
$next = $eu + $limit;
$nume = $dbo->query("select count(id) from receipt")->fetchColumn();
echo "<TABLE class='t1'>";
echo "<tr><th>ID</th><th>Name</th><th>Pass</th><th>Amount</th><th>Action</th></tr>";
$query=" SELECT * FROM receipt 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[name]</td><td>$row[phone_num]</td><td>$row[Amount]</td><td><a href='delete.php?id=$row[id]'>delete</a></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>";
}
?>
This is the code for delete.php which is linked.
<?php
require "config.php";
$pdo="null";
$sql = "DELETE FROM receipt WHERE ID= :ID";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':ID', $_GET['id'], PDO::PARAM_INT);
$stmt->execute($sql);
echo "Record deleted successfully";
header('location: currentout.php');
?>
The 'id' is being passed to the delete page but delete function is not executing. Can someone assist spot the error in delete.php??
You set $pdo to 'null' then you try to use it as an object. Enable error reporting and you would have seen a related error message.
Related
I am trying to convert a mySQL query to PDO.
I have partly got the data coming through as expected but I cannot get the entire query to pull the correct data. The mySQL query is able to pull 4 categories with the appropriate number of entries in each category being pulled and displayed. The PDO conversion query is only pulling 3 categories, and no entries in any category
I am assuming I have not converted the query correctly but I cannot find where the issue is.
I would also like some input on how to limit exposure to SQL injection with the new code.
OLD QUERY (Working)
function listPuppies(){
include("db_connect.php");
$query = " SELECT *
FROM tblLitters
WHERE available = 1
ORDER BY litBreed, litMother";
$resultOut = mysql_query($query, $connection) or die ("<br>Error in query: $query.".mysql_error($connection));
//Check if a row is returned
if (mysql_num_rows($resultOut) > 0) {
while($rowOut = mysql_fetch_array($resultOut)){
$litterID = $rowOut['litterID'];
$litMother = $rowOut['litMother'];
$litBreed = $rowOut['litBreed'];
$litBreedDate = $rowOut['litBreedDate'];
$litDesc = $rowOut['litDesc'];
$litterImage = $rowOut['litImage'];
$litterImageThumb = $rowOut['litterImageThumb'];
$litBreedCost = $rowOut['litBreedCost'];
if ($litterImageThumb == ''){
$litterPic = "";
}else{
$litterPic = "<img src=\"images/Litters/".$litterImageThumb."\" align=\"right\" style=\"padding:1px; margin:3px; border:6px solid #fff;\">";
}
echo "<table width=\"650\"><tr>\n";
if ($breed <> $rowOut['litBreed']){
$breed = $rowOut['litBreed'];
echo "</tr></table>\n";
echo "<br><br><div class=\"breedHead\">$breed's For Sale</div><hr color=\"#C5FBB4\">\n";
echo "<br><table width=\"650\" cellspacing=\"0\" cellpadding=\"5\"><tr><td colspan=\"3\"><table bgcolor=\"#044726\" width=\"100%\" border=\"1\" bordercolor=\"#137b48\" cellpadding=\"6\"><tr><td>".$litterPic."<span style=\"font-size:12pt;\">".$litDesc."<br><br><strong>Mother:</strong> $litMother<br><strong>Cost: </strong>$$litBreedCost<br><br></span></td></tr></table></td></tr><tr><td colspan=\"3\"> </td></tr>";
$counter = 0;
}else{
if ($pupLitterID <> $rowOut['litterID']){
echo "</table>\n";
echo "<br><br><br><table width=\"650\" cellspacing=\"0\" cellpadding=\"5\"><tr><td colspan=\"3\"><table bgcolor=\"#044726\" width=\"100%\" border=\"1\" bordercolor=\"#137b48\" cellpadding=\"6\"><tr><td>".$litterPic."<span style=\"font-size:12pt;\">".$litDesc."<br><br><strong>Mother:</strong> $litMother<br><strong>Cost: </strong>$$litBreedCost<br><br></span></td></tr></table></td></tr><tr><td colspan=\"3\"> </td></tr>";
$counter = 0;
}
}
$query = " SELECT *
FROM tblPuppies
WHERE litterID = $litterID";
$result = mysql_query($query, $connection) or die ("<br>Error in query: $query.".mysql_error($connection));
//$breed = $row['pupBreed'];
$counter = 0;
//Check is a row is returned
if (mysql_num_rows($result) > 0) {
//old table start
while($row = mysql_fetch_array($result)){
$status = $row['pupStatus'];
$pupLitterID = $row['litterID'];
if ($status == "For Sale"){
if ($row['pupOnHold'] == 1){
$status = '<font color=\"red\">On Hold</font>';
}
if ($row['pupSold'] == 1){
$status = '<font color=\"red\">Sold</font>';
}
}
if ($row['pupSex'] == 'F'){
$sex = 'Female';
}else{
$sex = 'Male';
}
//used to change popup window position depending on where thumbnail is palced on page
if ($counter == 0){
echo "<td width=\"33%\"><a class=\"thumbnailLeft\" href=\"#thumb\">";
}
if ($counter == 1){
echo "<td width=\"33%\"><a class=\"thumbnail\" href=\"#thumb\">";
}
if ($counter == 2){
echo "<td width=\"33%\"><a class=\"thumbnailRight\" href=\"#thumb\">";
}
echo "<div align=\"center\"><img src=\"images/ForSale/".$row['pupPicThumb']."\" style=\"padding:1px; border:6px solid #fff;\"><br>".$row['pupName']." - $sex<br><strong>$status</strong></div><span><img src=\"images/ForSale/".$row['pupPic']."\"></span></a><div align=\"center\">Contact Us About This Pup</div></td>";
if ($counter == 2){
echo "</tr><tr>\n";
$counter = -1;
if ($breed <> $rowOut['litBreed']){
$breed = $rowOut['litBreed'];
echo "</table>\n";
echo "<br><br><div class=\"breedHead\">$breed's For Sale</div><hr color=\"#C5FBB4\"><br>\n";
echo "<table width=\"95%\"><tr><td>".$litterPic."<span style=\"font-size:12pt;\">".$litDesc."<br><br><strong>Mother:</strong> $litMother<br><strong>Litter Birth Date: </strong>$litBreedDate<br><br></span></td></tr></table>";
echo "<table width=\"650\"><tr>\n";
$counter = -1;
}
}
$counter = $counter + 1;
}
echo "</tr></table>\n";
}else{
echo "There are no puppies left for sale in this litter, sorry.<br><br>Please check back again soon.";
}// End IF/ELSE
}//end outer while
}else{
echo "There are currently no puppies for sale.<br>Please check back again soon.";
}//end outer if
}
NEW QUERY (Not Working entirely)
function listPuppies(){
include("db_connect.php");
try {
$stmt = $connection->prepare("SELECT * FROM tblLitters WHERE available = 1");
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt->execute();
}
//Catch PDO Query Error
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
// set the resulting array to associative
//$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($stmt->fetchColumn() > 0) {
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $rowOut){
$litterID = $rowOut['litterID'];
$litMother = $rowOut['litMother'];
$litBreed = $rowOut['litBreed'];
$litBreedDate = $rowOut['litBreedDate'];
$litDesc = $rowOut['litDesc'];
$litterImage = $rowOut['litImage'];
$litterImageThumb = $rowOut['litterImageThumb'];
$litBreedCost = $rowOut['litBreedCost'];
if ($litterImageThumb == ''){
$litterPic = "";
}else{
$litterPic = "<img src=\"images/Litters/".$litterImageThumb."\" align=\"right\" style=\"padding:1px; margin:3px; border:6px solid #fff;\">";
}
echo "<table width=\"600\"><tr>\n";
if ($breed <> $rowOut['litBreed']){
$breed = $rowOut['litBreed'];
echo "</tr></table>\n";
echo "<br><br><div class=\"breedHead\">$breed's For Sale</div><hr color=\"#C5FBB4\">\n";
echo "<br><table width=\"600\" cellspacing=\"0\" cellpadding=\"5\"><tr><td colspan=\"3\"><table bgcolor=\"#044726\" width=\"100%\" border=\"1\" bordercolor=\"#137b48\" cellpadding=\"6\"><tr><td>".$litterPic."<span style=\"font-size:12pt;\">".$litDesc."<br><br><strong>Mother:</strong> $litMother<br><strong>Cost: </strong>$$litBreedCost<br><br></span></td></tr></table></td></tr><tr><td colspan=\"3\"> </td></tr>";
$counter = 0;
}else{
if ($pupLitterID <> $rowOut['litterID']){
echo "</table>\n";
echo "<br><br><br><table width=\"600\" cellspacing=\"0\" cellpadding=\"5\"><tr><td colspan=\"3\"><table bgcolor=\"#044726\" width=\"100%\" border=\"1\" bordercolor=\"#137b48\" cellpadding=\"6\"><tr><td>".$litterPic."<span style=\"font-size:12pt;\">".$litDesc."<br><br><strong>Mother:</strong> $litMother<br><strong>Cost: </strong>$$litBreedCost<br><br></span></td></tr></table></td></tr><tr><td colspan=\"3\"> </td></tr>";
$counter = 0;
}
}
$stmt1 = $connection->prepare("SELECT * FROM tblPuppies WHERE litterID = .$litterID.");
$counter = 0;
//Check if a row is returned
if ($stmt1->fetchColumn() > 0) {
//old table start
foreach ($stmt1->fetch(PDO::FETCH_ASSOC) as $rowOut){
$status = $row['pupStatus'];
$pupLitterID = $row['litterID'];
if ($status == "For Sale"){
if ($row['pupOnHold'] == 1){
$status = '<font color=\"red\">On Hold</font>';
}
if ($row['pupSold'] == 1){
$status = '<font color=\"red\">Sold</font>';
}
}
if ($row['pupSex'] == 'F'){
$sex = 'Female';
}else{
$sex = 'Male';
}
//used to change popup window position depending on where thumbnail is placed on page
if ($counter == 0){
echo "<td width=\"33%\"><a class=\"thumbnailLeft\" href=\"#thumb\">";
}
if ($counter == 1){
echo "<td width=\"33%\"><a class=\"thumbnail\" href=\"#thumb\">";
}
if ($counter == 2){
echo "<td width=\"33%\"><a class=\"thumbnailRight\" href=\"#thumb\">";
}
echo "<div align=\"center\"><img src=\"images/ForSale/".$row['pupPicThumb']."\" style=\"padding:1px; border:6px solid #fff;\"><br>".$row['pupName']." - $sex<br><strong>$status</strong></div><span><img src=\"images/ForSale/".$row['pupPic']."\"></span></a><div align=\"center\">Contact Us About This Pup</div></td>";
if ($counter == 2){
echo "</tr><tr>\n";
$counter = -1;
if ($breed <> $rowOut['litBreed']){
$breed = $rowOut['litBreed'];
echo "</table>\n";
echo "<br><br><div class=\"breedHead\">$breed's For Sale</div><hr color=\"#C5FBB4\"><br>\n";
echo "<table width=\"95%\"><tr><td>".$litterPic."<span style=\"font-size:12pt;\">".$litDesc."<br><br><strong>Mother:</strong> $litMother<br><strong>Litter Birth Date: </strong>$litBreedDate<br><br></span></td></tr></table>";
echo "<table width=\"600\"><tr>\n";
$counter = -1;
}
}
$counter = $counter + 1;
}
echo "</tr></table>\n";
}else{
echo "There are no puppies left for sale in this litter, sorry.<br><br>Please check back again soon.";
}// End IF/ELSE
}//end outer while
}else{
echo "There are currently no puppies for sale.<br>Please check back again soon.";
}//end outer if
}
Thanks in advance
I found my issue for the entries in categories not showing.
Within my query I tried SELECT * WHERE field1 = .$variable.
But I needed to bind the variable as a parameter instead, like so:
$stmt1 = $connection->prepare("SELECT * FROM tblPuppies WHERE litterID = :litterID");
$stmt1->bindParam(':litterID', $litterID);
$stmt1->execute();
This successfully populated my categories as expected.
It is worth noting that Your Common Sense's answer was right, however only answered part of my question. anyone else reading these answers should take note of both answers.
EDIT......
As pointed out by ShowDev, the
' if ($stmt->fetchColumn() > 0)'
condition advanced the count to the second row, and then only returned the remaining 3 records.
The link posted by ShowDev shows correct procedure for this type of query
get rid of if ($stmt->fetchColumn() > 0) condition
for this useless message change to this
$found = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($found) {
foreach ($found as $rowOut){
I have the code below and am trying to get the next 25 results from my sql table to appear on page. However, whenever I click the next button, no information is displayed. I have my offset = ($page - 1) * $items_per_page......I'm struggling to figure this out as it seems so simple compared the other code I've written, but is proving to be very elusive to me....any assistance would be greatly appreciated. My primary issue is that the next link does not provide the next 25 results and I'm unable to determine why and how to correct.
echo "<h3 style='text-align:center;'>Welcome to the Exchange Portal, " . $row['name'] . "! </h3>";
$items_per_page = 25;
$sql_count = "SELECT pin, title, title2, email, phone FROM crown_acura";
$result_cnt = mysqli_query($conn, $sql_count);
if(false === $result_cnt) {
throw new Exception('Query failed with: ' . mysqli_error());
} else {
$row_count = mysqli_num_rows($result_cnt);
// free the result set as you don't need it anymore
//mysqli_free_result($result_cnt);
}
echo $row_count;
echo " ";
if (!isset($_GET['Page'])) {
$Page = 1;
} else {
$Page = $_GET['Page'];
}
echo $page;
echo " ";
$page_count = 0;
if (0 === $row_count) {
// maybe show some error since there is nothing in your table
} else {
// determine page_count
$page_count = (int)ceil($row_count / $items_per_page);
// double check that request page is in range
if($page > $page_count) {
// error to user, maybe set page to 1
$page = 1;
}
}
echo " ";
echo $page_count;
echo " ";
echo $items_per_page;
$offset = ($page-1)*$items_per_page;
//echo $paging_info;
//echo " ";
echo "<br />";
//Query for displaying results
$list_sql = "SELECT pin, title, title2, email, phone FROM crown_acura LIMIT $offset, $items_per_page";
$result_query = $conn->query($list_sql);
//Table for displaying query results
echo "<table class='verify'>";
echo "<tr >";
echo "<td><h3>Name</h3></td><td> </td><td><h3>E-mail</h3></td><td><h3>Phone</h3></td>";
echo "</tr>";
for($i = 1; $i<= $page_count; $i++) {
if ($result_query->num_rows > 0) {
// output data of each row
while($row3 = mysqli_fetch_array($result_query)) {
echo "<tr>";
echo "<td class='dltd2 dlcl'>" . $row3["title"] . "</td><td>" . $row3["title2"] . "</td><td><a href='mailto:" . $row3['email'] . "'>" . $row3["email"] . "</a> </td><td>" . $row3["phone"] . " </td>";
echo "</tr>";
}
} else {
echo "0 results";
}
}
echo "<tr></tr>";
$next_page = $page + 1;
$last_page = $page - 1;
if($paging_info['curr_page'] <= 1) {
echo "<tr>";
echo "<td></td><td colspan='2'><a class='loadlink' href='" . $_PHP_SELF . "'>Next 25</a></td><td></td>";
echo "</tr>";
} elseif ($paging_info['curr_page'] < $page_count) {
echo "<tr>";
echo "<td></td><td><a href='" . $_PHP_SELF . "?page=" . $last_page . "'>Prev 25</a></td><td><a href='" . $_PHP_SELF . "?page=" . $next_page . "'>Next 25</a></td><td></td>";
echo "</tr>";
} elseif ($paging_info['curr_page'] === $page_count) {
echo "<tr>";
echo "<td></td><td colspan='2'><a href='" . $_PHP_SELF . "?page=" . $last_page . "'>Prev 25</a></td><td></td>";
echo "</tr>";
}
echo "</table>";
}
}
}
Have you tried to run the rendered SQL.
Output to browser:
"SELECT pin, title, title2, email, phone FROM crown_acura LIMIT $offset, $items_per_page"
try this... and change $page for different values (2,3,...,etc)
<?php
$items_per_page = 25;
$sql_count = "SELECT pin, title, title2, email, phone FROM crown_acura";
$result_cnt = mysqli_query($conn, $sql_count);
if (false === $result_cnt) {
throw new Exception('Query failed with: ' . mysqli_error());
} else {
$row_count = mysqli_num_rows($result_cnt);
// free the result set as you don't need it anymore
//mysqli_free_result($result_cnt);
}
echo $row_count;
echo " ";
if (!isset($_GET['Page'])) {
$Page = 1;
} else {
$Page = $_GET['Page'];
}
echo $page;
echo " ";
$page_count = 0;
if (0 === $row_count) {
// maybe show some error since there is nothing in your table
} else {
// determine page_count
$page_count = (int)ceil($row_count / $items_per_page);
// double check that request page is in range
if ($page > $page_count) {
// error to user, maybe set page to 1
$page = 1;
}
}
echo " ";
echo $page_count;
echo " ";
echo $items_per_page;
$offset = ($page - 1) * $items_per_page;
//echo $paging_info;
//echo " ";
echo "<br />";
//Query for displaying results
$list_sql = "SELECT pin, title, title2, email, phone FROM crown_acura LIMIT $offset, $items_per_page";
$result_query = $conn->query($list_sql);
echo ("RESULTS: ".$result_query->num_rows());
?>
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 hope that title makes sense.... Basically I created PHP script to take data from a database and display in, I then wrote some code to use a drop down menu to order that data. That all worked ok until I tried to utilise some pagination. I can make the pagination work, and I can make the ordering work, but not at the same time! At the moment the code that I have will allow me to order the list and almost paginate it. There are 40 results and I want to display 10 at a time. When not using the ordering code I can paginate it perfectly but when I try to intergrate the two bits of code it will only display the first 10 results and not give me an option to go to the next page to see the rest! (please bear in mind that I only started learning 5 das ago so I am still getting to grips with it!
The code:
if (!isset($_GET['start']))
{
$_GET['start'] = 0;
}
$per_page = 10;
$start = $_GET['start'];
if (!$start)
$start = 0;
$sort = #$_POST['order'];
if (!empty($sort)) {
$get = mysql_query("SELECT bookname, bookauthor, bookpub, bookisbn
FROM booktable
ORDER BY ".mysql_real_escape_string($_POST['order'])." ASC
LIMIT $start, $per_page");
}
else {
$get = mysql_query("SELECT bookname, bookauthor, bookpub, bookisbn
FROM booktable
ORDER BY bookname ASC
LIMIT $start, $per_page");
}
$record_count = mysql_num_rows($get);
?>
<?php
if (isset($_GET['showerror']))
$errorcode = $_GET['showerror'];
else
$errorcode = 0;
?>
wont include all the html rubbish and the ordering menu!
<div id="mid">
<?php
echo "<table>";
echo "<tr>";
echo "<th>";
echo "</th>";
echo "<th>";
echo "Book Title";
echo "</th>";
echo "<th>";
echo "Book Author";
echo "</th>";
echo "<th>";
echo "Book Publisher";
echo "</th>";
echo "<th>";
echo "Book ISBN";
echo "</th>";
echo "<th>";
echo "</th>";
echo "</tr>";
while ($row = mysql_fetch_assoc($get))
{
// get data
$bookname = $row['bookname'];
$bookauthor = $row['bookauthor'];
$bookpub = $row['bookpub'];
$bookisbn = $row['bookisbn'];
echo "<tr>";
echo "<td>";
echo "<a href='addtolist.php?bookname=".$bookname."&bookauthor=".$bookauthor."&bookpub=".$bookpub."&bookisbn=".$bookisbn."'>Add to basket</a>";
echo "</td>";
echo "<td>";
echo $bookname;
echo "</td>";
echo "<td>";
echo $bookauthor;
echo "</td>";
echo "<td>";
echo $bookpub;
echo "</td>";
echo "<td>";
echo $bookisbn;
echo "</td>";
echo "</tr>";
}
echo "</table>";
$prev = $start - $per_page;
$next = $start + $per_page;
if (!($start<=0))
echo "<a href='products.php?start=$prev'>Prev</a> ";
//set variable for first page number
$i=1;
//show page numbers
for ($x = 0; $x < $record_count; $x = $x + $per_page)
{
if ($start != $x)
echo "<a class='pagin' href='products.php?start=$x'> $i </a>";
else
echo "<a class='pagin' href='products.php?start=$x'><b> $i </b></a>";
$i++;
}
//show next button
if (!($start >= $record_count - $per_page))
echo "<a class='pagin' href='products.php?start=$next'> Next </a>";
?>
Thank you so much for reading!
Simpliest way just change $sort = #$_POST['order']; to $sort = #$_REQUEST['order']; and add to your pagination links &order=$order
I have tried my hand at some pagination but it gives me very unexpected results....
The first is that it on the first page of the pagination it seems to override the CSS and align all divs to the right hand side of the page... when you then click 'next' to view the next three results and so on the page goes back as per the CSS tells it!
The second problem is that the table displaying the results doesn't seem to work. The very first result on each page of the pagination is in the table, the next two results (three results per page) are displayed on the page however below and not in the table!
The code is quite long but here we go:
<?php
session_start();
if ( !isset($_SESSION['username']))
{
header("Location:index.php");
exit();
}
//connect to database
require "dbconn.php";
$per_page = 3;
$start = $_GET['start'];
$sort = #$_POST['order'];
if (!empty($sort)) {
$query = "SELECT bookname, bookauthor, bookpub, bookisbn
FROM booktable
ORDER BY ".mysql_real_escape_string($_POST['order'])." ASC";
}
else {
$query = "SELECT bookname, bookauthor, bookpub, bookisbn
FROM booktable
ORDER BY bookname ASC";
}
$results = mysql_query($query)
or die (mysql_error());
$record_count = mysql_num_rows($results);
if (!$start)
$start = 0;
$get = mysql_query("SELECT * FROM booktable LIMIT $start, $per_page");
?>
<?php
if (isset($_GET['showerror']))
$errorcode = $_GET['showerror'];
else
$errorcode = 0;
?>
Then I will cut out all the unnecesary html
<div id="mid">
<?php
echo "<table border='2px'>";
echo "<tr>";
echo "<th>";
echo "</th>";
echo "<th>";
echo "Book Title";
echo "</th>";
echo "<th>";
echo "Book Author";
echo "</th>";
echo "<th>";
echo "Book Publisher";
echo "</th>";
echo "<th>";
echo "Book ISBN";
echo "</th>";
echo "<th>";
echo "</th>";
echo "</tr>";
while ($row = mysql_fetch_assoc($get))
{
// get data
$bookname = $row['bookname'];
$bookauthor = $row['bookauthor'];
$bookpub = $row['bookpub'];
$bookisbn = $row['bookisbn'];
echo "<tr>";
echo "<td>";
echo "<a href='addtolist.php?bookname=".$bookname."&bookauthor=".$bookauthor."&bookpub=".$bookpub."&bookisbn=".$bookisbn."'>Add to basket</a>";
echo "</td>";
echo "<td>";
echo $bookname;
echo "</td>";
echo "<td>";
echo $bookauthor;
echo "</td>";
echo "<td>";
echo $bookpub;
echo "</td>";
echo "<td>";
echo $bookisbn;
echo "</td>";
echo "</tr>";
echo "</table>";
}
$prev = $start - $per_page;
$next = $start + $per_page;
if (!($start<=0))
echo "<a href='products.php?start=$prev'>Prev</a> ";
//set variable for first page number
$i=1;
//show page numbers
for ($x = 0; $x < $record_count; $x = $x + $per_page)
{
if ($start != $x)
echo "<a href='products.php?start=$x'>$i</a>";
else
echo "<a href='products.php?start=$x'><b>$i</b></a>";
$i++;
}
//show next button
if (!($start >= $record_count - $per_page))
echo "<a href='products.php?start=$next'>Next</a>";
?>
<?php echo $record_count; ?>
This is how the page looks (image 1) (the table border shows the problem)
As I said before I also get the problem when the list first gets displayed and the page ends up looking like this: (image2)
You can see how they differ!
I hope that I have made sense!
For starters, you have your </table> tag in your while loop. Change that and see if everything else falls into place.