How to group and show multiple resultset row values within a single table cell?

前端 未结 1 1547
遇见更好的自我
遇见更好的自我 2021-01-29 09:19


        
相关标签:
1条回答
  • 2021-01-29 10:09

    Most sensibly, you should use GROUP BY and GROUP_CONCAT() in your query to completely prepare your resultset.

    Something like this: (untested)

    SELECT pp_name, GROUP_CONCAT(pp_position SEPARATOR '<br>') AS pp_position
    FROM tbl_preset_position
    WHERE pp_status = 'Active'
    GROUP BY pp_name
    ORDER BY pp_name
    

    Then you can just echo out the data normally into your table.


    Otherwise, you'll need to use a convoluted bit of php to determine which rows should have appended data and which can stand alone...

    Now, I haven't tested this code, but I believe the conditional logic should hold up. You just need to ORDER BY pp_name then check for a new pp_name value as you iterate the resultset to determine if you are displaying the first in the group or not.

    I am using OO syntax for the query functions because it is less verbose.

    <?php
    include("functions/functions.php");
    
    echo '<button class="btn btn-primary">Back</button>';
    echo '<button class="btn btn-primary" data-toggle="modal" data-target="#addModal">Add Position Preset</button>';
    
    if (!$con = new mysqli("localhost", "root", "", "db_stvs")) {
        echo 'Connect failed: ', $con->connect_error);  // never display errors to the public
    } elseif (!$result = $con->query("SELECT pp_name, pp_position FROM tbl_preset_position WHERE pp_status = 'Active' ORDER BY pp_name")) {
        echo 'Syntax Error', $con->error;  // never show the exact error message to the public
    } elseif (!$result->num_rows) {
        echo 'No Active Records Found';
    } else {
        echo '<table class="table-bordered">';
            echo '<tr><th>Preset Name</th><th>Positions Available</th></tr>';
            $name = null;                                                            // establish a default value that won't be matched
            while ($row = $result->fetch_assoc()) {
                if ($row['pp_name'] !== $name) {
                    if ($name !== null) {
                        echo '</td></tr>';
                    }
                    echo "<tr><td>{$row['pp_name']}</td><td>{$row['pp_position']}";  // write row for pp_name group
                } else {
                    echo "<br>{$row['pp_position']}";                                // append all subsequent values in group
                }
                $name = $row['pp_name']; // update temporary variable
            }
            echo '</td></tr>';
        echo '</table>';
    }
    
    0 讨论(0)
提交回复
热议问题