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

前端 未结 1 1548
遇见更好的自我
遇见更好的自我 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 '
    ') 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.

    Back';
    echo '';
    
    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 '';
            echo '';
            $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 '';
                    }
                    echo "';
        echo '
    Preset NamePositions Available
    {$row['pp_name']}{$row['pp_position']}"; // write row for pp_name group } else { echo "
    {$row['pp_position']}"; // append all subsequent values in group } $name = $row['pp_name']; // update temporary variable } echo '
    '; }

    0 讨论(0)
提交回复
热议问题