counting records in a database

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
hward
Forum Contributor
Posts: 107
Joined: Mon Apr 19, 2004 6:19 pm

counting records in a database

Post by hward »

I just want to count how many records are in a table but can't seem to find anything on it.
hward
Forum Contributor
Posts: 107
Joined: Mon Apr 19, 2004 6:19 pm

think i got it

Post by hward »

Code: Select all

<?php

$db_name = " ";
$table_name = " ";
$connection = @mysql_connect("localhost", "username", "password") 
	or die("Couldn't connect.");

$db = @mysql_select_db($db_name, $connection)
	or die("Couldn't select database.");
	

$query = "SELECT COUNT(*) FROM $table_name"; 
$count = mysql_query($query) or die("Select Failed!");
$count = mysql_fetch_array($count);




?>
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<? echo $count[0]; ?>
</body>
</html>
?>
User avatar
phpScott
DevNet Resident
Posts: 1206
Joined: Wed Oct 09, 2002 6:51 pm
Location: Keele, U.K.

Post by phpScott »

Code: Select all

<?php
$query = "SELECT COUNT(someFieldName) as rowCount FROM $table_name"; 
$count = mysql_query($query) or die("Select Failed!");
$rowCount = mysql_fetch_array($count);
echo "total rows in table are ".$rowCount['rowCount'];
?>
User avatar
m3mn0n
PHP Evangelist
Posts: 3548
Joined: Tue Aug 13, 2002 3:35 pm
Location: Calgary, Canada

Post by m3mn0n »

You could also just run a normal query and use [php_man]mysql_num_rows()[/php_man].
User avatar
mudkicker
Forum Contributor
Posts: 479
Joined: Wed Jul 09, 2003 6:11 pm
Location: Istanbul, TR
Contact:

Post by mudkicker »

Code: Select all

<?php
$rowCount = mysql_fetch_array($count);
// this is even better -----v
$rowCount = mysql_fetch_assoc($count);
?>
Post Reply