Home > Software design >  Select how many distinct values there are in a column and display them
Select how many distinct values there are in a column and display them

Time:05-06

I have a table in my database called names and each row inside this table has a class, as follows:

Name Class
John Class-1
Isabel Class-2
Mark Class-1
Gabriel Class-2
Mike Class-2

As you can see, I have class-1 and class-2 repeat. What I want to do is get how many distinct classes there are (that is, in the example, class-1 and class-2) and for each class there are, I want to display the names corresponding to that class separately in different divs. So the output I want is:

<div>
 John
 Mark
</div>
<div>
 Isabel
 Gabriel
 Mike
</div>"

My current code is returning this: Class-1Class-1

when the second Class-1 should be Class-2;

the code I've got so far:

$query = "select distinct class from names order by class";
$result = mysqli_query($conn, $query);
$array = mysqli_fetch_array($result);
foreach($array as $class) {
  echo $class;
}

the code above is just a test to see if I was getting the correct "classes" in "class", but apparently I am not.

CodePudding user response:

In your code you are only processing ONE result row from your result set.

But because you are using mysqli_fetch_array without any parameter you get an assoc array and a numeric array so this one row as an array looks like

$array = ['class'=>'Class-1', '0' => 'Class-1'];

Hence the output you are getting.

If you want the output you suggest I would do

// select all the classes and names
$query = "select class,name from names order by class, name";
$result = mysqli_query($conn, $query);

$classes = [];  // add the names into an array
while ($row = $result->fetch_assoc() ){
    //load the classes names into seperate occurances of the array
    // now if you actually have 100 classes it will still work
    $classes[$row['class']][] = $row['name'] . '<br>';
}

Now in your HTML you can do

<?php
foreach ( $classes as $class ) {
    echo implode('<br>', $class) . '<br>';
}
?>

CodePudding user response:

You want to have a "select class, count() as classCount from names group by class order by class"*, then join it with your people list on class

Name Class classCount
John Class-1 2
Isabel Class-2 3
Isabel Class-1 2
Mark Class-2 3
Gabriel Class-2 3

Name Class John Class-1 Isabel Class-2 Mark Class-1 Gabriel Class-2 Mike Class-2

  • Related