Jump to content

[SOLVED] How to return the value of a mysql count query in php?


blurredvision

Recommended Posts

I'm familiar with mysqli_fetch_array when returning values and such, but for the first time, I'm needing to use the COUNT(*) function in mysql.  Here's my code:

 

$winsquery1 = "SELECT COUNT(*) FROM hometeam_stats WHERE gamertag_id='{$standings['gamertag_id']}' AND season='$currentseason' AND win_loss=1";
$runqueries1 = @mysqli_query($dbc, $winsquery1);

 

Usually, I would just set up $runqueries1 with the fetch array and go from there.  But how do I simply extract the number that my query should hopefully be getting?

You will still use mysql_fetch_array as you usually do except that you will use an index number instead of a field name

 

<?php
$result = mysql_fetch_array ($runqueries1);
$count = $result[0];
?>

Not necessarily you can do $result['COUNT(*)']

 

Howwer a better option would be give the count a name in your query, eg

$winsquery1 = "SELECT COUNT(*) as stats_count FROM hometeam_stats WHERE gamertag_id='{$standings['gamertag_id']}' AND season='$currentseason' AND win_loss=1";

And use $result['stats_count'] instead.

You could also just do it all in one query with mysql_result like so:

 

<?
$count = mysql_result(mysql_query("SELECT COUNT(*) FROM hometeam_stats WHERE gamertag_id='{$standings['gamertag_id']}' AND season='$currentseason' AND win_loss=1"), 0);

echo $count;
?>

Please don't get in the habit of nesting several functions, especially if the innermost can fail and return a FALSE value instead of the expected results as this prevents error checking, error reporting, error logging, and error recovery logic that would be present in a real application.

Archived

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

×
×
  • Create New...

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.