Are there any security concerns to consider when dynamically displaying columns in a table using PHP?

When dynamically displaying columns in a table using PHP, there is a security concern known as SQL injection. To prevent SQL injection attacks, it is important to sanitize user input and use prepared statements when constructing SQL queries. This helps to ensure that any user input is treated as data and not executable code.

// Example of using prepared statements to dynamically display columns in a table

// Assuming $selectedColumns is an array of selected columns
// Assuming $tableName is the name of the table

// Sanitize user input
$selectedColumns = array_map('mysqli_real_escape_string', $selectedColumns);

// Construct the SQL query with prepared statements
$query = "SELECT " . implode(", ", $selectedColumns) . " FROM " . mysqli_real_escape_string($tableName);

// Prepare and execute the query
$stmt = $mysqli->prepare($query);
$stmt->execute();

// Fetch results
$result = $stmt->get_result();

// Display table with dynamic columns
echo "<table>";
echo "<tr>";
foreach ($selectedColumns as $column) {
    echo "<th>" . $column . "</th>";
}
echo "</tr>";
while ($row = $result->fetch_assoc()) {
    echo "<tr>";
    foreach ($selectedColumns as $column) {
        echo "<td>" . $row[$column] . "</td>";
    }
    echo "</tr>";
}
echo "</table>";

// Close statement and connection
$stmt->close();
$mysqli->close();