Jump to content

Archived

This topic is now archived and is closed to further replies.

MrLarkins.com

What did I just do?

Recommended Posts

[code]$main = mysql_query("SELECT id FROM ibf_members WHERE mgroup=4");
$main = mysql_fetch_array($main);
$id = $main['id'];[/code]

here is my code.  I know for a fact that there are five entries in the database in column id where mgroup=4, however when i do
[code]$count = count($id);
print("$count");[/code]

i get 1

isn't $id an array here?  or did i do something wrong?

Share this post


Link to post
Share on other sites
yea you were a little bit off on the syntax..

If all you are wanting to do is count the number of rows you can use ether mysql_num_rows or mysql_result. I will give you an example for both.

The query will still be the same for both..
[code=php:0]
$main = mysql_query("SELECT id FROM ibf_members WHERE mgroup=4");
$count = mysql_num_rows($main);
echo $count;
[/code]

Or

[code=php:0]
$main = mysql_query("SELECT COUNT(id) AS id_count FROM ibf_members WHERE mgroup=4");
$id_count = mysql_result($main, 0, 'id_count');
echo $id_count;
[/code]

Both will do the same thing

Hope that helps,
Tom

Share this post


Link to post
Share on other sites
[quote author=MrLarkins.com link=topic=111381.msg451313#msg451313 date=1160739628]
[code]$main = mysql_query("SELECT id FROM ibf_members WHERE mgroup=4");
$main = mysql_fetch_array($main);
$id = $main['id'];[/code]

here is my code.  I know for a fact that there are five entries in the database in column id where mgroup=4, however when i do
[code]$count = count($id);
print("$count");[/code]

i get 1

isn't $id an array here?  or did i do something wrong?

[/quote]

$id isn't an array...$main is an array, with each element being a column in your table.  Right now, you're getting 1 because you've only accessed the id from the one record you've accessed.  Try doing this:

[code]
<?php

$query = "SELECT id FROM ibf_members WHERE mgroup=4";
$result = mysql_query($query);
$ids = mysql_num_rows($result); //returns the number of rows returned by your SELECT query

echo "$ids\n";
?>
[/code]

If you want to get to info from each returned row, you'll have to loop through them as the mysql_fetch functions only return one row at a time.  So something like:

[code]
<?php

$query = "SELECT * FROM ibf_members WHERE mgroup=4";
$result = mysql_query($query);

while($row = mysql_fetch_array($result)){ //while you have records available from the SELECT query
   /* process the record, typically with something like:
   $somevar = $row['somecolumn'];
   do something with $somevar */
} //loop automatically ends when there are no more records available from your SELECT query
?>
[/code]

Share this post


Link to post
Share on other sites

×

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.