Assign variable mysql count

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
kerick
Forum Newbie
Posts: 5
Joined: Mon Mar 17, 2003 12:42 pm

Assign variable mysql count

Post by kerick »

I want to assign $count the value of the following sql query
$SQL = "select count(*) from sublist;"

how do I do this.
User avatar
andre_c
Forum Contributor
Posts: 412
Joined: Sun Feb 29, 2004 6:49 pm
Location: Salt Lake City, Utah

Post by andre_c »

Code: Select all

$count = mysql_result($SQL, 0);
hope that helps
Illusionist
Forum Regular
Posts: 903
Joined: Mon Jan 12, 2004 9:32 pm

Post by Illusionist »

Code: Select all

$SQL = "select count(*) as count from sublist";
$result = mysql_query($SQL);
$result = mysql_fetch_assoc($result);
$count = $result['count'];
echo $count;
But if you just trying to get the number of rows, try this:

Code: Select all

$SQL = "select * from sublist";
$result = mysql_query($SQL);
$count = mysql_num_rows($result);
echo $count;
kerick
Forum Newbie
Posts: 5
Joined: Mon Mar 17, 2003 12:42 pm

not workng

Post by kerick »

I've stripped down the php and now have this

<?php
$usr ="root";
$pwd="test";
$db = "master";
$host ="localhost";

#connect to database
$cid = mysql_connect ($host, $usr,$pwd);
if (!$cid) {echo ("Error:") . mysql_error() . "\n"); }

?>

<?php

$SQL ="select * from sublist";
$result = mysql_query($SQL) or die ("die1");
$count = mysql_num_rows ($result) or die ("die2");

echo $count;
echo $SQL;
?>

I get die1

if I remove the or die I get an echo of the sql
Last edited by kerick on Fri Mar 12, 2004 5:49 pm, edited 1 time in total.
User avatar
andre_c
Forum Contributor
Posts: 412
Joined: Sun Feb 29, 2004 6:49 pm
Location: Salt Lake City, Utah

Post by andre_c »

You need to select the database:

Code: Select all

$db = mysql_select_db("$db", $cid) 
    or die ("Couldn't select database.");
also do die('Error 1:'.mysql_error()) instead of die1 and die2
Post Reply