query help

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
speedy33417
Forum Contributor
Posts: 128
Joined: Sun Jul 23, 2006 1:14 pm

query help

Post by speedy33417 »

How do I get the number items I query without looping out my result?

This problem is coming up for me as I'm working on a photo album. I display a thumb for each album that the user can select and list how many pictures are in that album, but obviously I wouldn't want display anything from those albums I only need the number of pictures.

Code: Select all

$sql = "SELECT picture_id FROM pictures
     WHERE picture_albumid = something";
$results = mysql_query($sql);
How do put the number of results in a variable?
Rovas
Forum Contributor
Posts: 272
Joined: Mon Aug 21, 2006 7:09 am
Location: Romania

Post by Rovas »

First read the PHP manual here http://php.net/manual/en/function.mysql-num-rows.php or you can use the COUNT statement in your query.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

Take a look at http://www.w3schools.com/sql/func_count_ast.asp
edit:
with a GROUP BY and JOIN you can pull the album + number of pictures all together with only one query.
User avatar
speedy33417
Forum Contributor
Posts: 128
Joined: Sun Jul 23, 2006 1:14 pm

Post by speedy33417 »

Awesome! That's exactly what I was looking for.

Thanks a bunch guys.
User avatar
speedy33417
Forum Contributor
Posts: 128
Joined: Sun Jul 23, 2006 1:14 pm

Post by speedy33417 »

Sorry. I gave it a try...

Code: Select all

$sql = "SELECT COUNT(*)
		FROM pictures
		WHERE picture_albumid = 1";
		
	$numofpics = mysql_query($sql);
	
	echo $numofpics;
And I get this echoed to the screen:

Resource id #7

What am I doing wrong?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Echoing a result resource. mysql_fetch_assoc() and it's siblings should be of interest.
shneoh
Forum Commoner
Posts: 38
Joined: Mon Sep 25, 2006 2:23 am
Location: Malaysia

Post by shneoh »

an easy function will help: mysql_num_rows().

It will shows number of rows in your query. Use it right after your query as following example:

Code: Select all

$sql = mysql_query("Select * from tableA where columnA = 1");

$nums = mysql_num_rows($sql);
echo $nums;
Post Reply