I have a method that returns data from a tournament system I am creating. I have an issue where the INNER JOIN query always returns one row, not matter if the WHERE clause is true or not.
In the database there are two tournaments, both with a T.game = ‘1’ – yet if I check the query for T.game = ‘2’, it still returns a row according to mysql_num_rows(), and when I print_r() the resulting array, it is empty except for the COUNT() row, yet shouldn’t the WHERE clause not find any rows and portray this accordingly to the mysql_num_rows() ?
I guess my main question is how do i stop the COUNT(P.id) from always displaying even when there are no matched rows in the tournaments table
public function fetchTournaments($gameID){
if($gameID == "" || $this->hasChar($gameID) || $this->hasSymb($gameID)){
$this->_errorMsg = "Invalid Game ID.";
return false;
}else{
$query = mysql_query("SELECT
T.id,
T.name,
T.description,
T.checkin,
DATE_FORMAT(T.date,'%b %d, %Y @ %h:%i %p') AS date,
COUNT(P.id) AS playernum
FROM tournaments T
INNER JOIN players P
ON T.id = P.tourney_id
WHERE T.game='{$gameID}'") or die(mysql_error());
$result = mysql_num_rows($query);
if($result > 0){
echo $result;
$output = mysql_fetch_array($query);
return $output;
}else{
$this->_errorMsg = "There are no tournaments for this game.";
return false;
}
}
}
In MySQL,
COUNT(like other aggregate functions) will always return a result. You may be able to get around this by usingGROUP BY, which will return the results of the aggregate for each row. You might want to play with the columns you list in theGROUP BY, but maybe something like: