How to output COUNT in php array?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • BaseballGraphs
    New Member
    • Sep 2010
    • 75

    #1

    How to output COUNT in php array?

    Hello,

    I keep getting the following error when I output the code below: Notice: Undefined property: stdClass::$coun t

    Code:
    $sql = "SELECT COUNT(name), name FROM searches GROUP BY name";
      $result = mysql_query( $sql );
      while($obj = mysql_fetch_object( $result ) ) {
      $pop_players = array();
      $pop_players['COUNT(name)'] = $obj->count;
      $pop_players['name'] = $obj->name;
      $pop_players_two[] = $pop_players;
      }
    How can I output COUNT(name) in an array?

    Thanks for your assistance.
  • johny10151981
    Top Contributor
    • Jan 2010
    • 1059

    #2
    give a new name to the count value as below
    Code:
    SELECT COUNT(name) as cnt, name FROM searches GROUP BY name
    and try
    Code:
    $obj->cnt;

    Comment

    • BaseballGraphs
      New Member
      • Sep 2010
      • 75

      #3
      Thanks very much! That works!

      Comment

      • BaseballGraphs
        New Member
        • Sep 2010
        • 75

        #4
        I am also trying to sort from HIGH to LOW by COUNT(name) or cnt. I seem to only be able to sort by the name...do you have any more suggestions. Here is my code so far:

        Code:
        $sql = "SELECT COUNT(name) as cnt, name FROM searches GROUP BY name DESC LIMIT 10";
          $result = mysql_query( $sql );
          while($obj = mysql_fetch_object( $result ) ) {
          $pop_players = array();
          $pop_players['name'] = $obj->name;
          $pop_players['COUNT(name)'] = $obj->cnt;
          $pop_players_two[] = $pop_players;
          krsort($pop_players_two);
          }
        
        foreach( $pop_players_two as $pop_players) { 
        [ $pop_players['name']; ] => $pop_players['COUNT(name)'];<br/>
        }
        ?>

        Comment

        • BaseballGraphs
          New Member
          • Sep 2010
          • 75

          #5
          This has been resolved by using ORDER BY.

          Code:
           $sql = "SELECT COUNT(name) as cnt, name FROM searches GROUP BY name ORDER BY COUNT(name) DESC LIMIT 10";

          Comment

          Working...