After adding pagination PHP function no longer displays mysql array data - php

I have made a PHP function that pulls data from a table (product_reviews) in my database, showing all reviews for a unique product_id. Here is the code:
function showReviews ($product_id)
{
include('database_conn.php');
$query = "SELECT * FROM product_reviews WHERE product_reviews.productID='".$product_id."'";
if ($queryresult = mysqli_query($conn, $query))
{
while ($currentrow = mysqli_fetch_assoc($queryresult))
{
$result_list[] = $currentrow;
}
foreach ($result_list as $currentrow)
{
$productitems[] = array(
$customer_forename = $currentrow['customer_forename'],
$customer_surname = $currentrow['customer_surname'],
$review_title = $currentrow['review_title'],
$review_text = $currentrow['review_text']);
echo '<article class="Review_Box">';
echo "<h3>".$review_title." by ".$customer_forename." ".$customer_surname."</h3></br>";
echo "<p>".$review_text."</p>";
echo "</article>";
}
}
}
This function is then called from the products page and it works as intended.
But when I add pagination to the function ( following an ehow tutorial), the function doesn't have any output(see here).
if(!function_exists('showReviews'))
{
function showReviews ($product_id)
{
include('database_conn.php');
include('functions.php');
$rowsPerPage = 3;
$currentPage = ((isset($_GET['page']) && $_GET['page'] > 0) ? (int)$_GET['page'] : 1);
$offset = ($currentPage-1)*$rowsPerPage;
$query = "SELECT * FROM product_reviews WHERE product_reviews.productID='".$product_id."' LIMIT '".$offset."','".$rowsPerPage."'";
if ($queryresult = mysqli_query($conn, $query))
{
while ($currentrow = mysqli_fetch_assoc($queryresult))
{
$result_list[] = $currentrow;
}
foreach ($result_list as $currentrow)
{
$productitems[] = array(
$customer_forename = $currentrow['customer_forename'],
$customer_surname = $currentrow['customer_surname'],
$review_title = $currentrow['review_title'],
$review_text = $currentrow['review_text']);
echo '<article class="Review_Box">';
echo "<h3>".$review_title." by ".$customer_forename." ".$customer_surname."</h3></br>";
echo "<p>".$review_text."</p>";
echo "</article>";
}
}
$count = countReviews (1);
$totalPages = $count/$rowsPerPage;
if($currentPage > 1)
{
echo 'Previous Page ';
}
if($currentPage < $totalPages)
{
echo 'Next Page';
}
}
}
I tested my sql query and it works fine in mysql Workbench.
What am I doing wrong? Can anyone recommend a better way to do this?

When you create your query, you are encapsulating the offset and limit between single quotes (if I read your code correctly).
SELECT * FROM product_reviews WHERE product_reviews.productID='25' LIMIT '0','3'
Try removing those single quotes.

Related

How to get the row number for each item returned

I am trying to use the XSwitch jquery script and dynamically create the "section id" automatically but am stuck.
How do I give each section an "id" starting at 0? Some items have 2 or 3 images, some have 30+.
$result = mysqli_query($conn,"SELECT * FROM Images WHERE stock=".$_GET['stock']." ORDER BY orderIndex");
while($row = mysqli_fetch_array($result)){
$count = $result->num_rows;
if ($count) {
$photos .= '<div class="section" id="section__NEED___NUMBER" style="background-image: url(inventory/'.$category.'/large/'.$stock.'_'.$row['id'].'.jpg)"></div>';
} else {
$photos = 'No Photos are currently available';
}
}
You can use a simple counter variable ($counter = 0;), which you increase on each loop ($counter++;`) -
$counter = 0;
$result = mysqli_query($conn,"SELECT * FROM Images WHERE stock=".$_GET['stock']." ORDER BY orderIndex");
$count = $result->num_rows;
if ($count) {
$photos = "";
while($row = mysqli_fetch_array($result)){
$photos .= '<div class="section" id="section__'.$counter.'" style="background-image: url(inventory/'.$category.'/large/'.$stock.'_'.$row['id'].'.jpg)"></div>';
$counter++;
}
} else {
$photos = 'No Photos are currently available';
}
note, you had your $count = $result->num_rows;if ($count) {...} inside your while() loop, when it should be outside.

Access return value from result() function

Trying to get the result of my query send it back to controller and return it to a view and access it there. I can't seem to display the value at my view so I tried echoing out what I got as a result from controller. It keeps stating undefined offset 1...please tell me how to access model return value properly
Model
$output = $this->db->query("SELECT * from incoming ORDER BY incomingId LIMIT 20");
return $output->result();
Controller
$data = $this->search_form->searchIdIncoming($searchQuery);
echo $data[0][1];
$this->load->view("searchIncoming", $data);
View
if(isset($incomingId))
echo "Primary key is available";
Try
echo $data[0]["Your Database field name"]; instead of echo $data[0][1];
like
echo $data[0]["id"];
If you want to display the result from model in view the most appropriate way is like this:
1) Return the resultant records from the model as an array like:
$output = $this->db->query("SELECT * from incoming ORDER BY incomingId LIMIT 20");
return $output->result();
2) Access this value in Controller by calling the function for this model query say (as you have not detailed well, I am not sure which function you are using),
$data['details'] = $this->search_form->searchIdIncoming($searchQuery); // store the result in an array
and pass the array to the view
$this->load->view("searchIncoming", $data);
3) In the view file, you can display the records with
if(!empty($details))
{
foreach($details as $row)
{
if($row->incomingId!=0)
echo "Primary key is available";
...........
}
}
I finally made it work by replacing the result() function with the result_array() function in codeigniter added a few other stuff to properly get table functions but here's the result I got:
$rows[] = array();
$rows2[] = array();
$rows3[] = array();
$i = 0;
$companyName = $this->db->query("SELECT id, name from company");
foreach($companyName->result_array() as $row2){
$rows2[$i]['id'] = $row2['id'];
$rows2[$i]['name'] = $row2['name'];
$i++;
}
//get all company names
$i = 0;
$staffName = $this->db->query("SELECT id, surname, firstName, middleInitial from employee");
foreach($staffName->result_array() as $row3){
$rows3[$i]['id'] = $row3['id'];
$rows3[$i]['name'] = $row3['surname'].", ".$row3['firstName']." ".$row3['middleInitial'];
$i++;
}
//get all employee names
$i= 0;
$output = $this->db->query("SELECT * from incoming ORDER BY incomingId LIMIT 20");
if ($output->num_rows() > 0) {
foreach($output->result_array() as $row){
$count = 0;
$j = 0;
$rows[$i]['incomingId'] = $row['incomingId'];
$rows[$i]['referenceNo'] = $row['referenceNo'];
$rows[$i]['documentTypeId'] = $row['documentTypeId'];
$rows[$i]['documentDate'] = $row['documentDate'];
$rows[$i]['dateReceived'] = $row['dateReceived'];
$rows[$i]['sender'] = $row['sender'];
while($count < sizeof($rows2)){
if($rows2[$j]['id'] != $row['companyId']){
$j++;
}else{
$rows[$i]['companyName'] = $rows2[$j]['name'];
break;
}
$count++;
}
$j= 0;
$count = 0;
while($count < sizeof($rows3)){
if($rows3[$j]['id'] != $row['responsibleStaffId']){
$j++;
}else{
$rows[$i]['responsibleStaffName'] = $rows3[$j]['name'];
break;
}
$count++;
}
$rows[$i]['subject'] = $row['subject'];
$rows[$i]['actionDone'] = $row['actionDone'];
$rows[$i]['track'] = $row['track'];
$rows[$i]['completed'] = $row['completed'];
$rows[$i]['remarks'] = $row['remarks'];
$i++;
}
return $rows;
}
return false;

Looping a Function like Wordpress have_posts

I am trying to loop a function through while similar to WordPress. I use the function to return a boolean of true or false. Now here is my function. Now, with it only returning true or false, I know that I have to get my function has_rows(); to change to false after it looks through all my rows. Is this possible?
So I guess my question is if it is possible, and how, to loop the a function in a while loop like the below example. I know it is possible because wordpress uses a function, my question is how.
THIS is what I have tried. And the loop wont stop.
function has_rows () {
global $Q_INFO;
global $DB_CONN;
static $COUNT; // STATIC TO REMEMBER LAST TIME FUNCTION CALLED
$COUNT = #$COUNT ? $COUNT++ : 0; // IF NOT SET, SET TO 0 AND COUNT EACH LOOP
echo $QUERY = "SELECT * FROM `" . $Q_INFO['table'] . "` LIMIT " . $COUNT . ", 1";
$STMT = $DB_CONN->prepare($QUERY);
$STMT->execute();
$RESULT = $STMT->get_result();
$STMT->close();
if ($RESULT->num_rows > 0) {
return true;
} else {
return false;
}
}
Im calling it just like in wordpress:
<?php if (has_rows()):?>
<?php while (has_rows()): ?>
Hi World!!
<?php endwhile; ?>
<?php endif; ?>
HERE IS MY FINAL CODE:
I had to add another static variable for the very first call of the function in if(has_rows()): and then I used the selected answer below to do the rest.
Thanks for the help guys!
function has_rows () {
global $Q_INFO;
global $DB_CONN;
static $I = 0;
static $COUNT = 0;
if ($I == 0) {
$QUERY = "SELECT * FROM `" . $Q_INFO['table'] . "`";
$I++;
} else {
$QUERY = "SELECT * FROM `" . $Q_INFO['table'] . "` LIMIT " . $COUNT . ", 1";
$COUNT++;
}
$STMT = $DB_CONN->prepare($QUERY);
$STMT->execute();
$RESULT = $STMT->get_result();
$STMT->close();
if ($I != 0) {
while ($ROW = $RESULT->fetch_assoc()) {
foreach ($ROW as $KEY=>$VALUE) {
$Q_INFO[$KEY] = $VALUE;
}
}
}
if ($RESULT->num_rows > 0) {
return true;
} else {
return false;
}
}
The first time you run it, $COUNT is 0, which evaluates to boolean false. So, $COUNT = #$COUNT ? $COUNT++ : 0; sets it to 0 again.
Just take out that line, explicitly initialize $COUNT to 0, and put $COUNT++; right before your final if statement.
function has_rows () {
global $Q_INFO;
global $DB_CONN;
static $COUNT = 0; // STATIC TO REMEMBER LAST TIME FUNCTION CALLED
// Other code here...
$COUNT++;
if ($RESULT->num_rows > 0) {
return true;
} else {
return false;
}
}
If your trying just to walk over an array, like the wordpress does, try this:
$posts = array('post1', 'post2', 'post3');
function has_posts()
{
// this line will make sure that you have a non empty array
if ( ! is_array($posts) or ! count($posts)) return false;
else return each($posts);
}
while ($post = has_posts())
{
echo $post;
}

PHP return an pagination object and displaying the links when called

I have this pagination class which I converted from a normal procedural function to a class since I started learning OOP. In the old procedural way, the function worked fine but I can't get this new class version to display on the screen
class Pagination {
public function __construct() {
}
/**
* This function is called whenever the there are several records to be displayed in the table
* This saves the page extending further down the page creating a long list of results
* when all the results can be spread across multiple pages
*/
public function pagination_one($total_pages, $page, $webpage) {
// Maximum number of links per page. If exceeded, google style pagination is generated
$max_links = 6;
$h=1;
if($page>$max_links) {
$h=(($h+$page)-$max_links);
}
if($page>=1) {
$max_links = $max_links+($page-1);
}
if($max_links>$total_pages) {
$max_links=$total_pages+1;
}
echo '<div class="page_numbers">
<ul>';
if($page>"1") {
echo '<li class="current">First</li>
<li class="current">Prev</li> ';
}
if($total_pages!=1) {
for ($i=$h;$i<$max_links;$i++) {
if($i==$page) {
echo '<li><a class="current">'.$i.'</a></li>';
}
else
{
echo '<li>'.$i.' </li>';
}
}
}
if(($page >="1")&&($page!=$total_pages)) {
echo '<li class="current">Next</li>
<li class="current">Last</li>';
}
echo '</ul> </div>';
}
and elsewhere in another class I want to create a new instance of that class and pass the method in the return along with some parameters
public function paging() {
if($this->getcount != 0) {
$this->paging = new Pagination();
return $this->paging->pagination_one($this->total_pages, $this->page, 'news');
}
}
When I try I var_dump() it comes up as NULL where I expect to see some pagination on the screen.
What have i got to change to be able to display the pagination? Do I have to created some variables in the Pagination class for $total_pages, $page and $webpage and initialise them in the constructor and remove them from the pagination_one method?
You do
return $this->paging->pagination_one...
when you are not returning anything in pagination_one -method, hence null.
I fixed it myself by removing the private variables in the class and changing the constructor.
The class now looks like this
class Pagination {
public function __construct($total_pages, $page, $webpage) {
$this->total_pages = $total_pages;
$this->page = $page;
$this->webpage = $webpage;
}
/**
* This function is called whenever the there are several records to be displayed in the table
* This saves the page extending further down the page creating a long list of results
* when all the results can be spread across multiple pages
*/
public function pagination_one() {
// Maximum number of links per page. If exceeded, google style pagination is generated
$max_links = 6;
$h = 1;
if($this->page > $max_links) {
$h=(($h + $this->page) - $max_links);
}
if($this->page >= 1) {
$max_links = $max_links + ($this->page - 1);
}
if($max_links > $this->total_pages) {
$max_links = $this->total_pages + 1;
}
$paging = '';
$paging .= '<div class="page_numbers">
<ul>';
if($this->page > "1") {
$paging .= '<li class="current">First</li>
<li class="current">Prev</li> ';
}
if($this->total_pages != 1) {
for ($i=$h; $i < $max_links; $i++) {
if($i == $this->page) {
$paging .= '<li><a class="current">'.$i.'</a></li>';
}
else {
$paging .= '<li>'.$i.' </li>';
}
}
}
if(($this->page >= "1" ) && ($this->page != $this->total_pages)) {
$paging .= '<li class="current">Next</li>
<li class="current">Last</li>';
}
$paging .= '</ul> </div>';
return $paging;
}
}
function pagination($sql_total_row, $post_per_page,$current_page=1, $url='', $lasturl = '', $parameter ='paging') {
$number_page = ceil($sql_total_row / $post_per_page);if($number_page<=1) return false;
$uls ='<ul class="pagination pagination-sm">';
$a = parse_url($url);
if(isset($a['query']))$url .= '&';else $url .= '?';
$url .= $parameter.'=';
$urls = '';
$distanc = 5;
$f = $current_page-$distanc;
$l = $current_page+$distanc;
$li = function($n,$link,$current_page){ return $current_page==$n ? '<li class="active"><span>'.$n.'</span><li>' : '<li>'.$n.'</li>'; };
for ($i = $current_page; $i > 0; $i--){
if($i>$f or $i < $distanc)
$urls = $li($i,$url.$i.$lasturl,$current_page). $urls;
else{
$i = $distanc;
$urls = '<li><span>...</span><li>'.$urls;
}
}
for ($i = $current_page+1; $i < $number_page; $i++){
if($i<$l or $i > $number_page - $distanc)
$urls .= $li($i,$url.$i.$lasturl,$current_page);
else{
$i = $number_page - $distanc;
$urls.= '<li><span>...</span><li>';
}
}
return $uls.$urls.'</ul>';
}
usage:
$total_row_sql = 1500; //required - get from mysql: SELECT FOUND_ROWS();
$row_display = 50; //required
$parameter_paged = (isset($_GET['paging'])) ? $_GET['paging'] : 1; // required
$custom_url = '/wordpress_url/?'; //custom
$hash = '#target_element_id'; //custom
$name_paramerter_paging = 'paging'; //custom
echo pagination($total_row_sql,$row_display,$parameter_paged,$custom_url,$hash,$name_paramerter_paging);
Result:
view result using pagination
========================================================================
Example if using loop from database:
function select( $table, $field='*', $where='', $order='') {
$sql = "select SQL_CALC_FOUND_ROWS $field from $table";
if($where) $sql.= " where $where";
if($order) $sql.= " order by $order";
$items = $wordpress_mysql->get_results( $sql );// custom: default result object, if u want parse array: ( $sql, ARRAY_A);
$sql_posts_total = $wordpress_mysql->get_var( "SELECT FOUND_ROWS();" );
return (object)['result'=>$items, 'total_rows'=>$sql_posts_total];
}
$result = select('user');
$data_items = $result->result;// foreach show database if u want
$sql_posts_total = $result->total_rows;
$post_per_page = 50;
$parameter_paged = (isset($_GET['paging'])) ? $_GET['paging'] : 1;
echo pagination($sql_posts_total,$post_per_page,$parameter_paged);

Confusion with `if` `else` and `while`

I have a code where it should check if the result equals to 8 it need to show something and if not it need to show something else and all of that happens inside of a while loop.
while ($row_fpages2 = mysql_fetch_array($result_fanpage2))
{
if ( $row_fpages2['client'] != NULL ) {
//GRAPHS
$sql = "SELECT likes, date FROM statistics_pages WHERE idnum = '".$idnum."' AND page_name = '".$row_fpages2['page_name']."' ORDER BY `statistics_pages`.`date` DESC LIMIT 8";
$result2 = mysql_query($sql) or die(mysql_error());
if ($result2) {
$data = array();
while ($row = mysql_fetch_assoc($result2)) {
$data[] = $row["likes"];
}
if ($result2 == 8) {
$c_data = count($data)-1;
$final = array();
for ($i = 0; $i < $c_data; $i++) {
$final[] = getZeroResult($data[$i], $data[$i+1]);
}
$data_string = join(",", $final);
$stats = '<img src="http://chart.apis.google.com/chart?chs=240x140&cht=ls&chd=t:0,0|'.$data_string.'&chg=20,20&chls=0.75,-1,-1|6,4,1&chm=o,FF9900,1,-1,7,-1|b,3399CC44,0,1,0"></img>';
} else {
$stats = '<img src="images/stats_un.jpg"></img>';
};
} else {
print('MySQL query failed with error: ' . mysql_error());
}
echo '...';
The problem is that the first output always showing the ( == 8) (even if it is not equals to 8) instead of the else output.
Then if i have 2 or more everything comes above the first one is correct but the first one is still showing the ( == 8).
Any help?
You do the following which is incorrect:
$result2 = mysql_query($sql) or die(mysql_error());
...
if ($result2 == 8) {
The return value of mysql_query is a resource not an int. What is that you are trying to do there ?
May be you would like to use
if(strlen($result2) == 8){
...
}
instead of
if($result2 == 8){
...
}
Hope that solves your problem.

Categories