What are the potential pitfalls of storing column names as variables in PHP when querying a database?

Storing column names as variables in PHP when querying a database can lead to SQL injection vulnerabilities if the variables are not properly sanitized. To prevent this, it is recommended to use prepared statements with parameterized queries to securely handle user input.

// Example of using prepared statements to safely query a database with column names stored in variables

$columnName = "column_name";
$columnValue = "some_value";

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

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM my_table WHERE $columnName = :value");

// Bind the parameter to the variable value
$stmt->bindParam(':value', $columnValue);

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

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

// Output the results
print_r($results);