Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I would like to know how can I count the results in case I have two loop ! :

$select = "SELECT X FROM Y"

$result = mysql_query($select,$link);

$total = mysql_num_rows($result);

while($row = mysql_fetch_array($result)) {

    $Name = $row['X'];
    $select2 = "SELECT id FROM `".$Name."` ";
    $result2 = mysql_query($select2,$link) or die ('Erreur : '.mysql_error() );
    $total2 = mysql_num_rows($result2);
    while($row2 = mysql_fetch_array($result2)) { echo $row2['id']} }

I would like to count how many id I have at the end . Thanks for your help

share|improve this question
Which result? Any idea? – chandresh_cool Apr 19 at 13:09
count many id I got at the end – Moon's Light Apr 19 at 13:12
see my answer @Moon's Light – chandresh_cool Apr 19 at 13:17
use SELECT COUNT(X) AS countX FROM Y – punk Apr 19 at 13:21

1 Answer

up vote 0 down vote accepted

just give this

$select = "SELECT X FROM Y"

$result = mysql_query($select,$link);

$total = mysql_num_rows($result);

$finalTotal=0;
while($row = mysql_fetch_array($result)) {

$Name = $row['X'];
$select2 = "SELECT id FROM `".$Name."` ";
$result2 = mysql_query($select2,$link) or die ('Erreur : '.mysql_error() );
$total2 = mysql_num_rows($result2);
 $finalTotal = $finalTotal + $total2;
while($row2 = mysql_fetch_array($result2)) { echo $row2['id'];} }

echo "total id is ".$finalTotal;

$finalTotal will show you total number of id's

share|improve this answer
That means I can obtain how many id I have without doing the second loop ? – Moon's Light Apr 19 at 13:19
You have to see my statement in second while loop i am adding the id's here $finalTotal = $finalTotal + $total2; – chandresh_cool Apr 19 at 13:20
this is generally not a good way count required <b> field </b> from Database – punk Apr 19 at 13:25
But here the query is fetching 'id' and obviously $result2 must have id and hence $count2 will inderctly give what we what, logically it works. – chandresh_cool Apr 19 at 13:27
it works but there's still a problem because I must do a limit 0,60 to limite the results otherwise I will have 100.000 results , this method just show exactly 60 results , how can I count all of them then ? – Moon's Light Apr 19 at 13:47
show 4 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.