'Display sql query result (from textarea input) into a table without knowing the number of columns

It starts off with the user having to input their query from a textarea.

<div class="querybar">
    <div class="form-item">
        <form action="" method="POST" class="simple-form">
        <textarea id="sqlquery" name="sqlquery" rows="3" cols="120" placeholder="Type your query here"></textarea>
    </div>
    <div class="form-item">
        <input type="submit" name="submit" value="Submit">
        </form>
    </div>
</div>

and then it should display the result of the query--if its a select statement--into a table regardless of the number of columns (example: I have productlist table which has 4 columns, and orders table with 8 columns, and it should be able to display all columns whether I query for 'productlist' or 'orders') otherwise it just displays a success message

if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit']))
{                 
    $sql = $_POST['sqlquery'];
    $trimmedSQL = trim($sql);
    
    if(!empty($trimmedSQL)) 
    {  
        $stmt = $db-> prepare($trimmedSQL);
        $stmt = execute();
        $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        if ( strstr( strtoupper($trimmedSQL), 'SELECT' ) )
        {
            //print all the results into a table
        } 
        else
        {
            echo "<div class = 'success-msg'><div><i class='fa-solid fa-circle-check'></i><b> Success!</b> Processed SQL query.</div></div>";
        }
    }
    else
    {
            echo "No query!";
    }
}

what should I place in place of the comment, for this to happen? or is it completely wrong? I'm sorry if this may sound like its already been answered before, but the answer I found didn't seem to work for my case.



Solution 1:[1]

Is it safe to do such a thing? if its safe you can do some thing like this instead of //print all the results into a table:

$output = "<table>";
$keys = array_keys($rows[0])
$output .= "<thead>";
foreach ($keys as $key ) {
    $output .= "<th>{$key}</th>";
}
$output .= "</thead><tbody>";

foreach ($rows AS $row) {
    $output .= "<tr>";
    foreach ($row as $key => $value) {
        $output .= "<td>{$value}</td>";
    }
    $output .= "</tr>";
}

$output .= "</tbody></table>";
echo $output;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1