gary falkland gary falkland - 17 days ago 8
PHP Question

How to show $classname only once

I am trying to echo $classname only once.
So it shows like this for example.

Puppy Dog

1st blah blah

2nd whoever

3rd extra

at present it shows like:

Puppy Dog

1st blah blah

Puppy Dog

2nd whoever

Puppy Dog

3rd extra



<?php

// SO UPDATE THE QUERY TO ONLY PULL THAT SHOW'S DOGS
$query = "SELECT c.* , p.* FROM result c,dogs p WHERE c.dog_id=p.dog_id";


$result = mysqli_query($connection, $query) or trigger_error
("Query Failed! SQL: $query - Error: ". mysqli_error
($connection), E_USER_ERROR);

if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$placement = $row['placement'];
$classname = $row['class_name'];
$dog_name = $row['dog_name'];
$award = $row['award'];




?>


<table>
<tr>
<td><strong><?php echo $classname ?></strong> </td><br>
</tr>
<tr>
<td><strong><?php echo $placement, $award ?></strong> <?php echo $dog_name ?></td>
</tr>
</table>








<?php }}} ?>




Answer

So, don't know why are you using <table> inside the while loop, this will print as per your no's of rows.

Here is the basic example, you can store the values in an array than use it with your HTML:

Example:

<?php
if ($result) {
  $myarr = array();
  while ($row = mysqli_fetch_assoc($result)) {
    $myarr[$row['class_name']][] = $row;  //store values into an array against each class in group
  }
}

foreach ($myarr as $key => $value) {
    echo "Class Name: ". $key."<br/>"; // will print class name
    foreach ($value as $fvalue) {
        echo "Placement: ".$row['placement']."<br/>";; // placement
        echo "Dog Name: ".$row['dog_name']."<br/>"; // dog name
        echo "Award: ".$row['award']."<br/>";; // award
    }
}
?>

Other solution is using incremental variable in while loop as mentioned in other answers.

Comments