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?

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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;
?>

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.