field count problem

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
Czar
Forum Commoner
Posts: 58
Joined: Sun Dec 29, 2002 11:17 am

field count problem

Post by Czar »

I try to count few values from DB table, and how many times same value repeats. So this is how it goes; I add records to DB including 'status'-field. The value of 'status' can be either win, draw or null (empty). When i try to count them, MySQL throws error if field is empty. I'm rather new with MySQL, so if somebody could check whats wrong with the script. It should just simply count the number of certain values repeating in table.

Here's the code:

## counts battles, wins, losses and draws and prints them ##

Code: Select all

<?php
include "inc/dbstart.php";
				 mysql_select_db("hivemind");
				 $countquery = "SELECT COUNT(*) as numRows FROM wars"; 
				 $count_played = mysql_result(mysql_query($countquery), 0, "numRows") or die(mysql_error());
				 $countquery2 = "SELECT COUNT(*) as numRows FROM wars WHERE status='won'";   
				 $count_won = mysql_result(mysql_query($countquery2), 0, "numRows") or die(mysql_error());
				 $countquery3 = "SELECT COUNT(*) as numRows FROM wars WHERE status='lost'"; 
				 $count_lost = mysql_result(mysql_query($countquery3), 0, "numRows") or die(mysql_error());
				 $countquery4 = "SELECT COUNT(*) as numRows FROM wars WHERE status='draw'"; 
				 $count_draw = mysql_result(mysql_query($countquery4), 0, "numRows") or die(mysql_error());
					 
           print "played: $count_played<br>\n";
           print "won: $count_won<br>\n";
           print "lost $count_lost<br>\n";
           print "even: $count_draw<br>\n";
					 mysql_close();
?>
[]InTeR[]
Forum Regular
Posts: 416
Joined: Thu Apr 24, 2003 6:51 am
Location: The Netherlands

Post by []InTeR[] »

If you just make a function to do this.

That gives the query with it.

Code: Select all

<?
function get_count($query){
  if(!$result = mysql_query($query)){
    echo mysql_error();
    echo $query;
    exit;
  }
  if($row = mysql_fetch_array($result)){
    return $row[0];
  }
  return FALSE;
}

use
$count_played = get_count($countquery);
instead of
$count_played = mysql_result(mysql_query($countquery), 0, "numRows") or die(mysql_error());
Czar
Forum Commoner
Posts: 58
Joined: Sun Dec 29, 2002 11:17 am

Post by Czar »

Works. Thx.
Post Reply