Page 1 of 1

field count problem

Posted: Tue May 13, 2003 12:40 am
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();
?>

Posted: Tue May 13, 2003 1:59 am
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());

Posted: Tue May 13, 2003 3:10 am
by Czar
Works. Thx.