Jump to content

[SOLVED] How to select COUNT() in PHP loop?


webmaster1

Recommended Posts

Hi All,

 

I need to pull one variable and it's count into a php page from its database. I can't get the count to work:

 

<?php
//CONNECT TO ADD TO EXPORT THE CATEGORY FIELD
include("dbinfo.php");
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");

//BUILD QUERY
$query="SELECT DISTINCT category, count( category ) FROM `masterdata` GROUP BY category";

$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();

//DISPLAY THE CATEGORY FIELD
$i=0;
while ($i < $num) {
$category=mysql_result($result,$i,"category");
$categorycount=mysql_result($result,$i,"count(category)");

echo "<a href='recordlist.php?category=$category'>$category</a></br>";
echo "<a href='recordlist.php?category=$categorycount'>$categorycount</a></br>";

$i++;
}
?>

 

Can anyone spot where I've gone wrong?

Link to comment
Share on other sites

$categorycount=mysql_result($result,$i,"count(category)");

needs to be

$categorycount=mysql_result($result,$i,"count( category )");

a better way is do set a name for count like this

$query="SELECT DISTINCT category, count( category ) AS count FROM `masterdata` GROUP BY category";

and then retrieving it like

$categorycount=mysql_result($result,$i,"count");

 

Scott.

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.