0
<table class="tbmed">     
 <tr> 
  <th>R1</th> 
  <th>R2</th>
  <th>R3</th>
  <th>R4</th>
 </tr>


<?php
include ("config.php");
$sql = "SELECT id, r1, r2, r3, r4  FROM table order by id DESC ";         
  
$result = $conn->query($sql);

if ($result->num_rows > 0) {
 
    while($row = $result->fetch_assoc()) 
    {
        echo "<tr><td>". 
        $row["r1"]. "</td><td>".
        $row["r2"]. "</td><td>". 
        $row["r3"]. "</td><td>". 
        $row["r4"].'  
        "</td></tr>";
    }
    echo "</table>";
} else {
    echo "0 results"; 
}
$conn->close();

?>     

I have some numerical data which are all positive, there may be repetitive values though. The above code gives the results like so:

R1 R2 R3 R4 
10 2  5  5
4  4  1  9
....

I'd like to sort the output in each row of the data table, and the result would be :

R1 R2 R3 R4 
2  5  5  10
1  4  4  9

How can I achieve this ? can someone help me please?

5
  • This would be easier I think if your database structure was more highly normalised (i.e. results all stored in a separate results table, with one result per row, and a foreign key back to the ID it belongs to) Commented May 10, 2022 at 12:33
  • 2
    With sort($row); before displaying? Commented May 10, 2022 at 12:33
  • I can't change db. I tried sort but couldn't get it done to get the results. Commented May 10, 2022 at 12:35
  • @JJ Then try natsort($row); Commented May 10, 2022 at 12:38
  • 1
    sort($row) will reset the array keys to a zero-based index. Instead of accessing the indices r1, r2 etc., you simply have to access 0, 1 etc. now. Commented May 10, 2022 at 12:39

1 Answer 1

1

You can use fetch_array instead fetch_assoc and apply sort function before output. Somehow like next:

if ($result->num_rows > 0) {
    while($row = $result->fetch_array(MYSQLI_NUM)) 
    {
        sort($row);
        echo '<td>';
        echo implode('</td><td>', $row);
        echo '</td>' . PHP_EOL;
    }
}

Try code online

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, Slava. Your code works, and simpler than mine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.