PHP - Search with Pagination - php

So I have these two PHP files products.php and receive.php .
What my problem is I want to use Ajax on displaying the products with search and paginates also. The code below works though but only if I use a GET. Is it possible to submit only the page number and refreshes only the div (where products loop) and not the whole page so that my POST requests (from search values - title, keywords) will still hold? coz if I use GET on pagination, the POST requests are getting empty after clicking the second page.
receive.php
$pdo_sql = 'SELECT * FROM items WHERE item_title LIKE %$keyword% OR keywords LIKE %$keyword% ORDER BY id DESC ';
/*** Pagination Code starts ***/
$per_page_html = '';
$page = 1;
$start=0;
// Get Page Number
if(!empty($_GET["page"])) {
$page = $_GET["page"];
$start=($page-1) * ROW_PER_PAGE;
}
// Adds Limit to Query then Execute
$limit=" LIMIT " . $start . "," . ROW_PER_PAGE;
$pagination_statement = $pdo_conn->prepare($pdo_sql);
$pagination_statement->bindValue(':keyword', '%' . $keyword . '%', PDO::PARAM_STR);
$pagination_statement->execute();
// Count the total number of rows
$row_count = $pagination_statement->rowCount();
if(!empty($row_count)){
$total_links=ceil($row_count/ROW_PER_PAGE);
$previous_link = $next_link = $page_link = '';
if($total_links > 4)
{
if($page < 5)
{
for($count = 1; $count <= 5; $count++)
{
$page_array[] = $count;
}
$page_array[] = '...';
$page_array[] = $total_links;
}
else
{
$end_limit = $total_links - 5;
if($page > $end_limit)
{
$page_array[] = 1;
$page_array[] = '...';
for($count = $end_limit; $count <= $total_links; $count++)
{
$page_array[] = $count;
}
}
else
{
$page_array[] = 1;
$page_array[] = '...';
for($count = $page - 1; $count <= $page + 1; $count++)
{
$page_array[] = $count;
}
$page_array[] = '...';
$page_array[] = $total_links;
}
}
}
else
{
for($count = 1; $count <= $total_links; $count++)
{
$page_array[] = $count;
}
}
for($count = 0; $count < count($page_array); $count++)
{
if($page == $page_array[$count])
{
// Current Page = Selected Page
$page_link .= '<a class="paginate_current" href="javascript:void(0)">'.$page_array[$count].'</a>';
$previous_id = $page_array[$count] - 1;
if($previous_id > 0)
{
// Previous Button Enable
$previous_link = '<a class="paginate_prev" href="products.php?page='.$previous_id.'">Previous</a>';
}
else
{
// Previous Button Disabled
$previous_link = '<a class="paginate_prev-disabled" href="javascript:void(0)">Previous</a>';
}
$next_id = $page_array[$count] + 1;
if($next_id > $total_links)
{
// Next Button Disabled
$next_link = '<a class="paginate_next-disabled" href="javascript:void(0)">Next</a>';
}
else
{
// Next Button Enabled
$next_link = '<a class="paginate_next" href="products.php?page='.$next_id.'">Next</a>';
}
}
else
{
if($page_array[$count] == '...')
{
// Ellipsis
$page_link .= '<a class="paginate_ellipsis" href="javascript:void(0)">...</a>';
}
else
{
// Pages
$page_link .= '<a class="paginate_pages" href="products.php?page='.$page_array[$count].'">'.$page_array[$count].'</a>';
}
}
}
$per_page_html .= '<div class="text-center paginate">';
$per_page_html .= $previous_link . $page_link . $next_link;
$per_page_html .= '</div>';
}
$query = $pdo_sql.$limit;
$pdo_statement = $pdo_conn->prepare($query);
$pdo_statement->bindValue(':keyword', '%' . $keyword . '%', PDO::PARAM_STR);
$pdo_statement->execute();
$pdo_result = $pdo_statement->fetchAll();
products.php
<div class="row">
<div class="col">
<div class="products_container grid" id="refresh">
<?php
if(!empty($pdo_result)) {
foreach($pdo_result as $pdo_row) {
$id = $pdo_row['id'];
$name = $pdo_row['item_title'];
$img = $pdo_row['item_img'];
$price = $pdo_row['item_price'];
$sold = $pdo_row['item_sold'];
$stocks = $pdo_row['stocks'];
$date = $pdo_row['date'];
if ($sold >= $max && $date != date("Y-m-d") ) {
$sort = 'hot';
}else if($date == date("Y-m-d") && $sold <= $max){
$sort = 'new';
}else{
$sort = '';
}
echo '
<div class="product grid-item '.$sort.'">
<div class="product_inner">
<div class="product_image">
<img src="'.$img.'" alt="">
<div class="product_tag">'.$sort.'</div>
</div>
<div class="product_content text-center">
<div class="product_title text-long">'.$name.'</div>
<div class="product_price">₱'.number_format($price).'</div>
<div class="product_button ml-auto mr-auto trans_200">
<button class="product_button ml-auto mr-auto trans_200" id="add2c" data-prod=" '.$id.' " type="button" >add to cart</button>
</div>
</div>
</div>
</div>
';
} //End Foreach Loop
}
else{
echo "no products found";
}
?>
</div>
</div>
</div>
<!-- PAGINATION HERE -->
<?php echo $per_page_html; ?>

Method 1 => Without ajax
You can use the GET method for search value also. and in every pagination link
append the search value too.
for example.
$next_link = '<a class="paginate_next" href="products.php?page='.$next_id.'">Next</a>';
instead of above line use below one.
$next_link = '<a class="paginate_next" href="products.php?page='.$next_id.'&search='.$keyword.'">Next</a>';
Method 2 => using ajax
instead of href use a javascript function like below
$next_link = '<a class="paginate_next" href="#" onclick="paginate_fn(\''.$next_id.'\', \''.$keyword.'\'">Next</a>'
<script>
function paginate_fn(pageID, keyword){
$.ajax({
async: true,
type: 'get', // you can use post also
dataType:'json',
data: {'pageID':pageID, 'keyword': keyword},
url: "paget_name.php", // your page name
success: function (data) {
$('#search-content').html( data['content'] );
},
error: function () {
alert('An Error Occurred!.');
}
});
}
</script>

Related

for loop not working correctly with json encode Php

I am trying to fetch members ratings from the database using ajax. I passed a function to the JSON, even though it returned a value in the function but it doesn't execute the for loop condition.
Here is my code, the loop failed to execute. What am I doing wrong?
function mrate($irate) {
$class = "fa-star star-filled";
for ($i = 0; $i < 5; $i++) {
if ($irate <= $i) {
$class = "fa-star-o empty";
}
return '<i class="fa ' . $class . '"></i>';
}
}
$perPage = 2;
if (isset($_GET["page"]) && isset($_GET["page"])) {
$page = $_GET["page"];
$pid = $mysqli->real_string_escape($_GET["pid"]);
} else {
$page = 1;
$pid = $mysqli->real_string_escape($_SESSION['pid']);
};
$startFrom = ($page - 1) * $perPage;
$sqlQuery = "SELECT id, name,
review, rating, added_date
FROM review_rating
where product_id = '$pid'
ORDER BY id ASC LIMIT $startFrom, $perPage";
$result = mysqli_query($mysqli, $sqlQuery);
$paginationHtml = '';
while ($row = mysqli_fetch_assoc($result)) {
$img = '<img class="rounded-circle" width="50" src="' . $set['installUrl'] . 'assets/img/login.png" alt="' . $row["name"] . '"/>';
$irate = $row['rating'];
$paginationHtml .= '<div class="product-review pb-4 mb-4 border-bottom">';
$paginationHtml .= '<div class="d-flex mb-3">';
$paginationHtml .= '<div class="media media-ie-fix align-items-center mr-4 pr-2">' . $img;
$paginationHtml .= '<div class="media-body pl-3"><h6 class="font-size-sm mb-0">' . $row["name"] . '</h6>';
$paginationHtml .= '<span class="font-size-ms text-muted">' . $row['added_date'] . '</span></div></div>';
$paginationHtml .= '<div><div class="star-rating">' . mrate($irate) . '</div></div>';
$paginationHtml .= '</div>';
$paginationHtml .= '<p class="font-size-md mb-2">' . $row['review'] . '</p>';
$paginationHtml .= '</div>';
}
$jsonData = array(
"html" => $paginationHtml,
);
echo json_encode($jsonData);
Replace your function mrate($irate) with this and try. You needed to concatenate the stars code to display it more than once.
function mrate($irate){
$stars = '';
for($i=0; $i<5; $i++){
if($irate <= $i){
$class = "fa-star-o empty";
}else{
$class = "fa-star star-filled";
}
$stars .= '<i class="fa '.$class.'"></i>';
}
return $stars;
}
Assuming there's no fractional rating, you can do the following - Display all 5 stars but solid ones will represent the rating.
function mrate($irate){
$class = '';
for($i = 0; $i < 5; $i++){
if ($irate <= $i) {
$class .= '<i class="fa fa-star"></i>';
} else {
$class .= '<i class="fa fa-star-o"></i>';
}
}
return $class;
}

How to count result according level number to be word put in the treeview?

I have a question to count each level of tree. For example, I am first line in the treeview, so that I am level 1, than my downline is stand level 2, my downline's downline is stand level 3 and so on. My question is how to take each level number change as word put into my treeview.
Below is my coding:
<?php
$sql_select = 'SELECT * FROM users WHERE id = ' . $user_id;
$query_select = db_conn_select($sql_select);
$i=1;
$level= 'Level';
foreach ($query_select as $rs_select) {
$email2 = $rs_select['email'];
$name2 = $rs_select['name'];
}
$lang = $_COOKIE["Language"];
require_once("language/lang_team_" . $lang . ".php");
?>
<!-- Level tree -->
<div class="row">
<!-- block -->
<div class="col-lg-12">
<div class="box">
<header>
<h5><?php echo $language["LIST_TITLE"]; ?>:</h5>
<!-- .toolbar -->
<!--div class="toolbar">
<nav style="padding: 8px;">
<a href="javascript:;" class="btn btn-default btn-xs collapse-box">
<i class="fa fa-minus"></i>
</a>
</nav>
</div--><!-- /.toolbar -->
</header><br><br>
<div class="block">
<div class="block-content collapse in">
<div class="span6">
<?php
$sql = "select * from level_tree lt JOIN users u ON lt.user_id = u.id where lt.referal_id =" . $user_id . ' and lt.level=1';
$query = mysql_query($sql);
if (mysql_num_rows($query) > 0) {
$select_name = 'SELECT * FROM users WHERE id = ' . $user_id;
$query_select = db_conn_select($select_name);
foreach ($query_select as $rs_select) {
$name = $rs_select['name'];
$email = $rs_select['email'];
$email_arr = explode('#', $rs_select['email']);
$email_length = strlen($email_arr[0]);
$email_first = substr($email_arr[0], 0, 1);
$email_last = substr($email_arr[0], -1, 1);
}
$email_address = '';
for ($i = 0; $i < $email_length; $i++) {
if ($i == 0) {
$email_address.=$email_first;
} elseif ($i == $email_length - 1) {
$email_address.=$email_last;
} else {
$email_address.='*';
}
}
$email_user = $email_address . '#' . $email_arr[1];
?>
<div id="jstree" style="font-size:15px;">
<ul>
<li><b><?php echo "<b> ".$level." ".$i.": ".$name2." (".$email2.")"; ?></b></li>
<ul>
<?php
while ($rs = mysql_fetch_array($query)) {
$email_address = '';
$email_arr = explode('#', $rs['email']);
$email_length = strlen($email_arr[0]);
$email_first = substr($email_arr[0], 0, 1);
$email_last = substr($email_arr[0], -1, 1);
for ($i = 0; $i < $email_length; $i++) {
if ($i == 0) {
$email_address.=$email_first;
} elseif ($i == $email_length - 1) {
$email_address.=$email_last;
} else {
$email_address.='*';
}
}
$email_user = $email_address . '#' . $email_arr[1];
echo "<li><b><img src='images/down_right_arrow.png' />".$level."&nbsp".$i.": ".$rs['name']." (".$email_user.")";
// echo "<li><b>" . $email_user . "";
downline_list($rs['id']);
echo "</b></li>";
}
?>
</div>
<?php
} else {
// echo $email2;
//echo "<b> ".$name2." (".$email2.")";
echo '<div style="font-size:15px;color:black;font-weight:bold;"><img src="images/down_right_arrow.png /><span style="font-size:15px;color:black;font-weight:bold;"> '.$name2.' ('.$email2.')</span></div>';
echo "<br />";
}
function downline_list($id) {
$sql = "select lt.user_id,lt.referal_id,lt.`level`,u.email,u.name from level_tree lt JOIN users u ON lt.user_id = u.id where lt.referal_id =" . $id . " and u.is_active=1 and lt.level=1";
$query = mysql_query($sql);
if (mysql_num_rows($query)) {
echo "<ul>";
while ($rs = mysql_fetch_array($query)) {
$email_address = '';
$email_arr = explode('#', $rs['email']);
$email_length = strlen($email_arr[0]);
$email_first = substr($email_arr[0], 0, 1);
$email_last = substr($email_arr[0], -1, 1);
$level = 'Level';
for ($i = 0; $i < $email_length; $i++) {
if ($i == 0) {
$email_address.=$email_first;
} elseif ($i == $email_length - 1) {
$email_address.=$email_last;
} else {
$email_address.='*';
}
}
$email_user = $email_address . '#' . $email_arr[1];
echo "<li><b><img src='images/down_right_arrow.png' />".$level." ".$i.": ".$rs['name']." (".$email_user.")";
// echo "<li><b>" . $email_user;
downline_list($rs['user_id']);
echo "</b></li>";
}
echo "</ul>";
}
$i++;
}
?>
</ul></div>
</div>
</div>
</div>
</div>
<!-- /block -->
</div>
<script src="plugins/jstree/dist/jquery-1.10.2.min.js"></script>
<link rel="stylesheet" href="plugins/jstree/dist/themes/default/style.min.css" />
<script src="plugins/jstree/dist/jstree.min.js"></script>
<script>
$(function() {
// 6 create an instance when the DOM is ready
$('#jstree').bind("ready.jstree", function() {
$('#jstree').jstree('open_all');
}).jstree();
});
</script>
<style type="text/css">
.jstree li > a > .jstree-icon { display:none !important; }
</style>
My output show in below the picture, it can show the number as word, but the number is the wrong to get in each level:
Actually I want the output result like the below picture, the level of number will count according to the level :
I am stuck in this question few days, hope someone can help me solve the big problem. Thanks.
Your code is about exploring the tree in a depth-first search (DFS) manner and find the level of each node in such a search (of course with different approach you can do it in breadth-first search manner as well). So, you should recursively call the downline_list function and send the level of the current node as a parameter.
In the main while, you are in the level one and by recursively calling the function, level increases by one in each recursive call. When you are exploring level $level of your tree, and you call downline_list function to find out the children of the current node, the direct children would be in $level + 1 and so on.
So you have something like this:
/// Main while loop
while ($rs = mysql_fetch_array($query)) {
// ...
downline_list($rs['id'], 1);
// ...
}
function downline_list($id, $level)
{
//...
//Nodes here are in level $level
//but the children of this node would be in level $level + 1
downline_list($rs['user_id'], $level + 1);
//...
}

Limiting bootstrap pagination in PHP to 5 pages

I'm trying to create pagination in PHP where 5 pages are displayed.
When on the first page we have:
[1][2][3][4][5] ...[325][>>]
Clicking on [325] will take you to that page (the last record), clicking on the right arrow will take you to page [2].
When on the second page we have:
[<<][1]...[2][3][4][5][6] ...[325][>>]
And when on the last page we have:
[<<][1]...[321][322][323][324][325]
I've been researching on how to do this without much luck. I think I understand that I need to create an array with adjacent pages of 2 on each side of the active page, when we are on any page except the first or last page. I also need to create an <li>1</li>
and
<li><?php echo $last_record; ?></li>
for when a user is anywhere but the first or last record.
I have the following code which works great, however when we start getting a large number of records, the pagination count gets ridiculous.
<ul class="pagination pull-left pagination-md">
<?php
// Creates back button in pagination
if(isset($page)) {
if($page > 1) {
$page_minus = $page-1;
echo "<li><a href='blog.php?page=$page_minus'> « </a></li>";
}
}
?>
<?php
global $con;
$q_pagination = mysqli_prepare($con, "SELECT COUNT(*) FROM admin_panel WHERE ");
$q_pagination->execute();
$result_pagination = $q_pagination->get_result();
$rows_result = $result_pagination->fetch_array();
$total_rows = array_shift($rows_result);
$post_per_page = $total_rows/15;
$post_per_page = ceil($post_per_page);
for($i = 1; $i <= $post_per_page; $i++) {
if(isset($page)){
if($i == $page) {
echo "<li class='active'><a href='blog.php?page=$i'>$i</a></li>";
}
else {
echo "<li><a href='blog.php?page=$i'>$i</a></li>";
}
}
}
// Creates the forward button in pagination
if(isset($page)){
if($page+1 <= $post_per_page) {
$page_plus = $page+1;
echo "<li><a href='blog.php?page=$page_plus'> » </a></li>";
}
}
?>
</ul>
I'll admit, after researching and attempting to make this work I'm just getting twisted in the logic. Does anyone have any thoughts on how to best approach this? Leads, current examples, etc. Most of what I've found is dated, incomplete, or stupid long.
<?php
session_start();
include "mysqli_connect.php";
$companyID = $_SESSION['compid'];
$db = new Database();
$dbc = $db->getConnection();
$display = 3; //number of records per page
$pages;
$dbb = new Database();
$dbcb = $dbb->getConnection();
$stat = "select * from reservationStatus where resStatId = '$companyID' ";
$r = mysqli_query($dbcb, $stat);
//variable for sorting - default is for registration date
$sort = (isset($_GET['sort'])) ? $_GET['sort'] : 'rd';
switch ($sort)
{
case 'ln':
$orderby = 'uniquenumber ASC';
break;
case 'fn':
$orderby = 'status ASC';
break;
case 'rd':
$orderby = 'resId ASC';
break;
case 'em' :
$orderby = 'resDate ASC';
break;
default:
$orderby = 'resId ASC';
break;
}
if(isset($_GET['p']) ) //already calculated
{
$pages=$_GET['p'];
}
else
{
//get the total number of records from the table
$q = "select count(resId) from reservation where companyID = '$companyID'";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_NUM);
$records=$row[0];
if($records > $display ) //$display is the number of records per page
//ceil rounds fractions up to integer value
$pages=ceil($records/$display);
else
$pages = 1;
}
//now determine where in the database to start
if(isset($_GET['s']) ) //already calculated
$start=$_GET['s'];
else
$start = 0;
//$q = "select * from users LIMIT $start, $display";
$q = "select * from reservation where companyID = '$companyID' order by $orderby LIMIT $start, $display";
$r = mysqli_query($dbc, $q);
if($r)
{
echo '<br />';
//display a table of results
echo '<div class="container">';
echo '<h1> Your Orders </h1>';
echo '<table align="center" class="table table-bordered table-striped" width="60%">';
echo '<tr bgcolor="#87CEEB">
<td><b>View</b></td>
<td><b>Change Status</b></td>
<td><b> Reference Number</b></td>
<td><b>Status</b></td>
<td><b>Date</b></td>
<td><b>Total Price</b></td></tr>';
//above is the header
//loop below adds the user details
//use the following to set alternate backgrounds
$bg = '#eeeeee';
while($row = mysqli_fetch_array($r))
{
$stat = "select * from reservationStatus where resStatusId = $row[7] ";
$rr = mysqli_query($dbcb, $stat);
$roww = mysqli_fetch_array($rr);
$bg = ($bg=='#eeeeee' ? '#ffffff' : '#eeeeee');
echo '<tr bgcolor="' . $bg. '">
<td>View</td>
<td>Change Status </td>
<td>'.$row[2].'</td>
<td>'.$roww[1].'</td>
<td>'.$row[1]. ' ' . $row[8].'</td>
<td>'.$row[3].'</td>
</tr>';
}
echo '</table></div>';
}
else
{
echo '<p class="error">' . $q . '</p>';
echo '<p class="error"> Oh dear. There was an error</p>';
echo '<p class="error">' . mysqli_error($dbc) .'</p>';
}
mysqli_free_result($r);
//makes links to other pages if required
if($pages > 1)
{
echo '<br /><p> ' ;
//find out what page we are on
$currentpage = ($start/$display)+1;
//need a previous button if not first page
if($currentpage != 1)
{
echo ' <a href="viewOrdersForCompanies.php?$s=' . ($start - $display) .
'&p=' .$pages . '&sort='.$sort.'">&nbspPrevious&nbsp</a>';
}
//create the numbered pages
for($i = 1; $i <= $pages; $i++)
{
if($i != $currentpage)
{
//the 's' paramater is used in the link to determine which the value
// in the LIMIT clause used in the select statement near the top of the page
echo '<a href="viewOrdersForCompanies.php?s=' . (($display * ($i-1))) . '&p='
. $pages . '&sort='.$sort.'">&nbsp' . $i . '&nbsp</a>';
}
//&nbsp is a character to insert a whitespace
}
//if not last page create next button
if($currentpage != $pages)
{
echo '<a href="viewOrdersForCompanies.php?s=' . ($start+$display) . '&p=' . $pages
. '&sort='.$sort.'">&nbspNext&nbsp</a>';
}
echo '</p>';
}
?>

unable to display :active page in my pagination function

am using following function to display pagination
public function paginationLinks(){
$outputString = "";
$q = $this->db->query('SELECT COUNT(*) FROM videos');
$res = $q->fetch();
$newsNumber = $res[0];
$q->closeCursor();
for($i = 1; $i <= ceil($newsNumber / $this->newsByPage); $i++){
$outputString .="<li><a href='?page=" . $i . "'>" . $i . "</a></li> ";
}
return $outputString;
}
and this is how i display
<ul class="pagination pagination-sm">
<?php echo $news->paginationLinks(); ?>
</ul>
now bootstrap doesn't display active page its because of function
how do i add some more option like next, previous and :active
just replace your function with this one
public function paginationLinks(){
$outputString = "";
$crpage = isset($_GET['page']) && trim($_GET['page']) != ''?trim($_GET['page']):1;
$q = $this->db->query('SELECT COUNT(*) FROM videos');
$res = $q->fetch();
$newsNumber = $res[0];
$q->closeCursor();
for($i = 1; $i <= ceil($newsNumber / $this->newsByPage); $i++){
if($crpage == $i){
$outputString .="<li class='active'><a href='?page=" . $i . "'>" . $i . "</a></li> ";
}else{
$outputString .="<li><a href='?page=" . $i . "'>" . $i . "</a></li> ";
}
}
return $outputString;
}
For next or previous see that link
great example for PHP pagination.
Please try this .I hope this help you
public function paginationLinks(){
$num_rec_per_page = 10;
$outputString = "";
$page = (isset($_GET['page']) && $_GET['page'] != '') ? trim($_GET['page']) : 1;
$start_from = ($page-1) * $num_rec_per_page;
$q = $this->db->query('SELECT COUNT(*) FROM videos');
$res = $q->fetch();
$total_records = $res[0];
$q->closeCursor();
$total_pages = ceil($total_records / $num_rec_per_page);
$outputString .= "<li><a href='?page=1'>".'|<'."</a></li>"; // Goto 1st page
if($page > 1){
$prev = $page - 1;
$outputString .= "<li><a href='?page=".$prev."'>Prev</a></li>"; // Goto previous page
}
for ($i=1; $i<=$total_pages; $i++) {
$activeClass = ($page == $i) ? 'active' : '';
$outputString .="<li class=".$activeClass."><a href='?page=" . $i . "'>" . $i . "</a></li> ";
}
if($page < $total_pages){
$next = $page + 1;
$outputString .= "<li><a href='?page=".$next."'>Next</a></li>"; // Goto Next page
}
if($page > 1){
$outputString .= "<li><a href='?page=".$total_pages."'>".'|>'."</a></li>"; // Goto last page
}
return $outputString;
}

Using Pagination on product view using Category ID

I feel I have asked alot of questions recently and Im sorry if this is relatively simple but I am struggling to get this working correctly.
I want to add pagination to my product view but when I add the pagination numbers code as seen at the bottom of the page they do not show.
I'm also aware that I should be using mysqli but I want to get this working first before moving over.
Thanks.
Show Product
<div class="link" style="width:100%; height:100%; background-color: white">
<?php
include("../script/dbconnect.php");
include("../script/get_product.php");
$posts = get_posts(null, $_GET['id']);
foreach ( $posts as $post ) {
if ( ! category_exists('name', $post['name']) ) {
$post['name'] = 'Uncategorised';
}
?>
<ul class='featured'>
<li class='headhighlight'><?php echo $post['title']; ?></li>
<li class='pricehigh'><?php echo $post['price']; ?></li>
<li class='imagefeat'><img class='imagelink' src='<?php echo $post['picture']; ?>' alt='$name'></li>
</ul>
<?php
}
?>
</div>
get_product.php
<?php
function get_posts($id = null, $cat_id = null) {
$posts = array();
//Pagination Code
$perpage = 10;
if(isset($_GET["page_num"]))
{
$page_num = intval($_GET["page_num"]);
}
else
{
$page_num = 1;
}
if ($page_num < 1)
{
$page_num = 1;
}
$calc = $perpage * $page_num;
$start = $calc - $perpage;
//End pagination code
$query ="SELECT `products`.`id` AS `name` , `products_cat`.`id` AS `category_id` , `products`.`name` AS `title` , `description` , `price` , `sale` , `picture`
FROM `products`
INNER JOIN `products_cat` ON `products`.`prod_id` = `products_cat`.`id` ";
if ( isset($id) ) {
$id = (int) $id;
$query .= " WHERE `products`.`id` = {$id}";
}
if ( isset($cat_id) ) {
$cat_id = (int) $cat_id;
$query .= " WHERE `products_cat`.`id` = {$cat_id}";
}
$query .= " ORDER BY `products`.`price` DESC Limit $start, $perpage";
$query = mysql_query($query);
echo mysql_error();
while ( $row = mysql_fetch_assoc($query) ) {
$posts[] = $row;
}
return $posts;
}
Pagination Code - to add page numbers - would be placed in showproduct.php
<p class="pagination">
<?php
if(isset($page_num))
{
$result = mysql_query("SELECT COUNT(*) As Total FROM products");
$rows = mysql_num_rows($result);
if($rows)
{
$rs = mysql_fetch_array($result);
$total = $rs["Total"];
}
$totalPages = ceil($total / $perpage);
if($page_num <=1 )
{
echo '<span id="page_links" style="font-weight:bold;"> < </span>';
}
else
{
$j = $page_num - 1;
echo '<span><a id="page_a_link" href="../admin/admin.master.php?page=list_products.php&page_num=' . $j . '"> < </a></span>';
}
for($i=1; $i <= $totalPages; $i++)
{
if($i<>$page_num)
{
echo '<span>' . $i . '</span>';
}
else
{
echo '<span id="page_links" style="font-weight:bold;">' . $i . '</span>';
}
}
if($page_num == $totalPages )
{
echo '<span id="page_links" style="font-weight:bold;">Next ></span>';
}
else
{
$j = $page_num + 1;
echo '<span> > </span>';
}
}
?>
</p>
$posts = get_posts(null, $_GET['id']);
$result = mysql_query($posts);
In the get_posts function you declare this variable as an array, fill it from a query result and then you return it... so it will never work. What were you trying to do here? You have to pass a string to the mysql_query function with correct MySQL query structure.
EDIT: adding the part of the code that is giving problems, and a possible fix.
$posts = get_posts(null, $_GET['id']);
$i = 0;
foreach ($posts as $post){
....
does it work this way? You already did the query with the LIMIT inside the get_posts function and returned the data.
$posts = get_posts(null, $_GET['id']);
returns array, of something. After it you trying to make mysql_query(array); Try to make
var_dump($posts); and copy print here. Or try next:
$posts = get_posts(null, $_GET['id']);
foreach($posts as $post){
$result[] = mysql_query($posts);
}

Categories