What are the best practices for selecting columns in a MySQL query in PHP to prevent SQL injection?

To prevent SQL injection when selecting columns in a MySQL query in PHP, it is important to use parameterized queries with prepared statements. This helps to separate the data from the SQL commands, preventing malicious input from altering the query structure. By binding parameters to the query, you can ensure that user input is treated as data rather than executable code.

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// User input for column selection
$selectedColumn = $_GET['column'];

// Prepare the SQL query with a parameterized statement
$stmt = $pdo->prepare("SELECT :column FROM my_table");
$stmt->bindParam(':column', $selectedColumn, PDO::PARAM_STR);

// Execute the query
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Output the results
foreach ($results as $row) {
    echo $row[$selectedColumn] . "<br>";
}