Getting Value of COUNT - php

I have a php pagination script that I found online ( http://papermashup.com/easy-php-pagination/), and it works fine and i want to modify it to better suit my needs and update it a little bit. The problem i am having is that whilst it gives the number of results found, using
echo $total_pages.' Results';
It will not return a zero if there are no results it just simply has no value.
Here is the code that counts the number of results.
$query = "SELECT COUNT(*) as num FROM $tableName";
$total_pages = mysql_fetch_array(mysql_query($query));
$total_pages = $total_pages[num];
I have tried to add an if statement so that if the results are 0 i can say sorry no matches found, but i can not get the value to display if there are no results.
I have tried to echo COUNT as a row along with num but no matter what i do, i can not seem to get it to display 0 results.

Extending on your code:
$query = "SELECT COUNT(*) as num FROM {$tableName}";
$total_pages = mysql_fetch_array(mysql_query($query));
$total_pages = $total_pages['num'];
if (!empty($total_pages)) {
echo $total_pages . " Results found.";
} else {
echo "Sorry! No results found.";
}

You can achieve this by using the function mysql_num_rows();
$result_set = mysql_query($query);
$count = mysql_num_rows($result_set);
p.s. please try to use mysqli rather than simple mysql as its deprecated now.

Try it.
$query = mysql_query("SELECT * FROM $tableName");
$num = mysql_num_rows($query);
if($num > 0)
{
echo "Total records = ".$num;
}
else
{
echo "Sorry no record found";
}

Related

How to echo result from query

Maybe I am overthinking this, but I have narrowed my query to find a row down to 1 result that I need, and it will not display. Wondering if someone could tell me what I am doing wrong.
$result = mysqli_query($link, "SELECT pageid FROM article ORDER BY id DESC LIMIT 1");
$row = mysqli_use_result($result);
echo $row;
I have it selecting the last row and supplying me with the stored data from the pageid of the last row.
I had to adapt my code. I believe it was because I use mysql. However, this code will work if you use mysqli
$pageid = "SELECT pageid FROM articles ORDER BY id DESC LIMIT 1";
$resultpageid = $link->query($pageid);
if ($resultpageid->num_rows > 0) {
while ($row = $resultpageid->fetch_assoc()) {
$pagenumber = $row["pageid"];
}
} else {
echo "0 results";
}
mysqli doesn't have any function to get a single column from a single row. You need to use one of the fetch methods e.g. fetch_array(). You don't need any loop if you use LIMIT 1.
Just fetch a single row and get the column from the returned array:
$pageid = "SELECT pageid FROM articles ORDER BY id DESC LIMIT 1";
$resultpageid = $link->query($pageid);
$row = $resultpageid->fetch_assoc();
// or
$row = $resultpageid->fetch_array();
if ($row) {
echo $row["pageid"];
} else {
echo "No record found!";
}

ajax-php star rating system (just show the average date from mysql databse)

I need a rating system which shows the average ratings in php. I done the rating process (saving and update process). I need just to show the average rating in php (using php-Ajax rating system).
While I retrive the data from the database I got errors. The code is this:
<?php
$con = mysql_connect("localhost","root","");
if(!$con){
echo "Connection to the Database Console was Unsuccessful";
}
$select = mysql_select_db("oilandgas13",$con);
if(!$select){
echo "Connection to the Database was Unsuccessful";
}
$add_coun= "SELECT sum(rating) sum, count(id) count from comments WHERE item_id = $itemID AND status=1";
$result = mysql_query($add_coun,$con);
if(!$result)
{
echo "query was not successfully";
}
$result = mysql_fetch_object($result);
$sum = $result->sum;
$count = $result->count;
$rating = $sum / $count;
echo $rating;
?>
I got errors like this:
Warning: mysql_fetch_object(): supplied argument is not a valid MySQL result resource in C:\wamp\www\final work_apr51\final work_apr51\calculation.php on line 19
Warning: Division by zero in C:\wamp\www\final work_apr51\final work_apr51\calculation.php on line 23
Maybe this can help you?
$link = mysqli_connect("localhost","mysqlusername","mysqlpassword","dbname");
$rating = mysql_real_escape_string($_GET['id']);
$q = mysqli_query($link,"SELECT * FROM ratings WHERE id='{$rating}'"); //Get our ratings by the page that has rated
//Die if id dont exist!
if(mysqli_num_rows($q) == 0) die("Wrong page id!");
//Select good & bad ratings
$good = mysqli_query($link,"SELECT * FROM ratings WHERE id='{$rating}' AND value ='yes'");
$bad = mysqli_query($link,"SELECT * FROM ratings WHERE id='{$rating}' AND value ='no'");
//Count good & bad ratings
$gcnt = mysqli_num_rows($good);
$bcnt = mysqli_num_rows($bad);
//Calculate
$totalVotes = $gcnt + $bcnt;
if($totalVotes == 0){
echo $totalVotes." votes";
}
if($totalVotes > 0){
echo "<font color='green'>".$totalVotes." votes</font>";
}
if($totalVotes < 0){
echo "<font color='red'>".$totalVotes." votes</font>";
}

related articles on post page

<?php
mysql_select_db($database_XXX, $XXX);
$result= mysql_query("SELECT COUNT(*) FROM news");
$total = mysql_result($result, 0, 0);
// create a random number
mt_srand((double)microtime()*1000000);
$number = mt_rand()%$total;
// get a random entry
$result= mysql_query("SELECT * FROM news LIMIT $number, 5");
$row = mysql_fetch_array($result);
?>
This is the PHP code I'm using and it pulls up random data from the table I want but I can't seem to figure out how to have it not show the current post it's on. Will I need to throw in an if statement in? If I do where would it go and how to impletment it. The only thing I can thing of is using if statements to check if the post_id on page matches the post_id posted. But I'm new to this and the only thing I can think of is.
if(!$row['post_id'] == $_GET['id']) {
}
I don't know what to make it do after. Also if anyone knows how or can help point me in the right direction that would be great. Thanks.
Here is the update of the total thing here. It still shows post it's already on. hope this helps. This is the php code for the page.
<?php
mysql_select_db($database_xxx, $xxx);
$result= mysql_query("SELECT COUNT(*) FROM news");
$total = mysql_result($result, 0, 0);
// create a random number
mt_srand((double)microtime()*1000000);
$number = mt_rand()%$total;
// get a random entry
$result= mysql_query(sprintf("SELECT * FROM news WHERE post_id <> %d LIMIT %d, 3", $post->post_id, $number));
$row = mysql_fetch_array($result);
?>
<?php
if (! isset($_GET['id']) || (int) $_GET['id'] === 0 ) {
echo "Incorrect input, aborting";
exit;
}
mysql_select_db($database_xxx, $xxx);
$sql = "SELECT * FROM news WHERE post_id = " . $_GET['id'];
// a line of debug to make sure things are as expected
$query = MYSQL_QUERY($sql);
// query your table for a match with post_id
if (mysql_num_rows($query) == "1")
// if a record is found, show the info
{
$fetch = mysql_fetch_array($query); // set $fetch to have the values from the table
} else {
echo "No match in database found."; // if no match is found, display this error
}
?>
Assuming that code is on the page where you view the main product:
$result= mysql_query(sprintf("SELECT * FROM news WHERE id <> %d LIMIT %d, 5", $post->id, $number));
Also, you should not be using mysql_* functions anymore as they are deprecated; checkout PDO

Trouble setting PHP variable in if statement

I have an Ajax call to create an image gallery. There is a combo box to set the number of images per page, and pagination to navigate through the pages. It's working fine, except that if a person is on the last page, and they increase the number of images per page, it reloads to the current page number. This is a problem because there are now less pages and so the page is blank. In other words, you end up on page 7 of 5 for instance.
I reckon the problem is in the PHP as that is where the number of pages is calculated. I've thought out an if statement to deal with this:
if ($page > $no_of_paginations) {
$page = $no_of_paginations;
}
However, I don't know where to place this. The reason being, $page needs to be defined before the mysql_query, but $no_of_paginations is defined after the query.
Any thoughts on how I can make this functional?
I'll post the pertinent code below:
<?php
$page = 0;
if(isset($_GET['page'])){
$page = (int) $_GET['page'];
}
$cur_page = $page;
$page -= 1;
if((int) $_GET['imgs'] > 0){
$per_page = (int) $_GET['imgs'];
} else {
$per_page = 16;
}
$start = $per_page * $page;
include"db.php";
$query_pag_data = "SELECT `imgURL`,`imgTitle` FROM `images` ".
"ORDER BY `imgDate` DESC LIMIT $start, $per_page";
$result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error());
echo "<ul class='new_arrivals_gallery'>";
while($row = mysql_fetch_assoc($result_pag_data)) {
echo "<li><a target='_blank' href='new_arrivals_img/".$row['imgURL']."' class='gallery' title='".$row['imgTitle']."'><img src='new_arrivals_img/thumbnails/".$row['imgURL']."'></a></li>";
}
echo "</ul>";
/* --------------------------------------------- */
$query_pag_num = "SELECT COUNT(*) AS count FROM images";
$result_pag_num = mysql_query($query_pag_num);
$row = mysql_fetch_array($result_pag_num);
$count = $row['count'];
$no_of_paginations = ceil($count / $per_page);
?>
Thanks for your help!
As you are currently doing it, there would be no problem with moving the last section to above the main query.
A better way to find the total records with MySQL is to use the SQL_CALC_FOUND_ROWS keyword on your main query (so here it is SELECT SQL_CALC_FOUND_ROWS imgURL, imgTitle FROM images WHERE etc) then you can query SELECT FOUND_ROWS() and just get the number of records found in the last query. As well as being faster and more efficient, this avoids a race condition when records are added between the two queries.
However, in this case you should probably just do the two current queries in the reverse order as your only other option is to check at the end and repeat if necessary.
You should use query:
$query_pag_data = "SELECT SQL_CALC_FOUND_ROWS `imgURL`,`imgTitle` FROM `images` ".
"ORDER BY `imgDate` DESC LIMIT $start, $per_page";
And instead of
$query_pag_num = "SELECT COUNT(*) AS count FROM images";
use
$query_pag_num = "SELECT FOUND_ROWS()";
If you do the "SELECT COUNT(*) ..." query earlier in the script (at least before the other query), you will have $no_of_paginations earlier, and can use it to clamp $page to the correct range.
Sometimes you just have to bite the bullet and do a query twice. Accept the user-provided "I want page X" value, and try to get that particular page. If it ends up being past the end of the available data, you can either say "hey, wait... that ain't right" and abort, or redo the loop and default to the last available page.
while(true) {
$sql = "select sql_calc_found_rows .... limit $X,$Y";
$result = mysql_query($sql) or die(mysql_error());
$sql = "select found_rows();"; // retrieve the sql_calc_found_rows_value
$res2 = mysql_query($sql);
$row = mysql_fetch_array($res2);
$total_rows = $row[0];
if ($total_rows < $requested_row) {
... redo the loop and request last possible page ...
} else {
break;
}
}
details on found_rows() function here.

Creating multiple pages from sql query

I am trying to create multiple pages from my query. If I have 100 results, and I want 10 results per page, I would like there to be ten pages created, with each page showing a different query. This is how my query is set up:
$sql ="SELECT * FROM Post WHERE (active ='1') ORDER BY PostID DESC ";
$result = mysql_query($sql,$db);
$numrows = mysql_num_rows($result);
while(($post = mysql_fetch_assoc($result))) {
$posts[] = $post;
}
<?php
if (!$numrows){ echo $errormessage;}
else{
foreach($posts as $post): ?>
echo stripslashes($post['text']);
<?php endforeach; }?>
This pulls each "post" from the database and puts displays them all out.
I would like to do something like this:
$results = mysql_num_rows($result);
$numpages = 10/$results; //gives the number of pages
while($numpages<$results)
{
//run code from above\\
}
What is the best way to do this with the method that I use? I appreciate your opinions because I'm at one of those stages where I'm lost in my own logic. Thank You!
Most pagination examples fail to meet real life requirements. A custom query string, for example.
So, here is a complete yet concise example:
<?
per_page=10;
// Let's put FROM and WHERE parts of the query into variable
$from_where="FROM Post WHERE active ='1'";
// and get total number of records
$sql = "SELECT count(*) ".$from_where;
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
$row = mysql_fetch_row($res);
$total_rows = $row[0];
//let's get page number from the query string
if (isset($_GET['page'])) $CUR_PAGE = intval($_GET['page']); else $CUR_PAGE=1;
//and calculate $start variable for the LIMIT clause
$start = abs(($CUR_PAGE-1)*$per_page);
//Let's query database for the actual data
$sql = "SELECT * $from_where ORDER BY PostID DESC LIMIT $start,$per_page";
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
// and fill an array
while ($row=mysql_fetch_array($res)) $DATA[++$start]=$row;
//now let's form new query string without page variable
$uri = strtok($_SERVER['REQUEST_URI'],"?")."?";
$tmpget = $_GET;
unset($tmpget['page']);
if ($tmpget) {
$uri .= http_build_query($tmpget)."&";
}
//now we're getting total pages number and fill an array of links
$num_pages=ceil($total_rows/$per_page);
for($i=1;$i<=$num_pages;$i++) $PAGES[$i]=$uri.'page='.$i;
//and, finally, starting output in the template.
?>
Found rows: <b><?=$total_rows?></b><br><br>
<? foreach ($DATA as $i => $row): ?>
<?=$i?>. <?=$row['title']?><br>
<? endforeach ?>
<br>
Pages:
<? foreach ($PAGES as $i => $link): ?>
<? if ($i == $CUR_PAGE): ?>
<b><?=$i?></b>
<? else: ?>
<?=$i?>
<? endif ?>
<? endforeach ?>
It would be hideous to extract all data from the database and manage it from PHP. It would kill the RAM, and the network.
Use the LIMIT clause for paging.
First, you need to see the total number of records. Use
$query = 'SELECT count(1) as cnt FROM Post WHERE active =1';
then,
$result = mysql_query($query, $db);
$row = mysql_fetch_assoc($result);
$count = $row['cnt'];
$pages = ceil($count/10.0); //used to display page links. It's the total number of pages.
$page = 3; //get it from somewhere else, it's the page number.
Then extract the data
$query = 'SELECT count(1) as cnt FROM Post WHERE active =1 LIMIT '.$page*10.', 10';
$result = mysql_query($query, $db);
while($row = mysql_fetch_assoc($result))
{
//display your row
}
Then output the data.
I'm using that similar code to do that:
$data = mysql_query("SELECT * FROM `table`");
$total_data = mysql_num_rows($data);
$step = 30;
$from = $_GET['p'];
$data = mysql_query("SELECT * FROM `table` LIMIT '.$from.','.$step.'"
That code get total rows
and that for creating links:
$p=1;
for ($j = 0 ; $j <= $total_data+$step; $j+=$step)
{
echo ' '.$p.' ';
$p++;
} ?>
You can also read about : pagination

Categories