Search code examples
phpmysqlmode

Get the mode values of a column


I have a table (sample below) which contains results from a phone vote

Number  Voted 
 97867  Dog
 97868  Cat
 97869  Dog
 97870  Dog
 97871  Cat
 97872  Donkey 

I query the data using

  $stmt =   $pdo->query( "SELECT * from data_mobile_api  " )  ;
  $voting = $stmt->fetch(PDO::FETCH_ASSOC);

What I want to do is get the most votes for a particular animal (The winners is etc) , however I would need to do this dynamically as the response from the text could be anything . So far I have pulled all the data into an array

  $animal = $voting['Voted']
  $votes[$animal] += 1

What I have is an array of $votes but I dont know how I can get the animal with the highest response,

Can anyone offer a way to do this or any better solution please ? hope all this all makes sense , thanks


Solution

  • Let mysql do the job:

    $sql = "SELECT Voted, COUNT(Number) FROM table GROUP BY Voted";