How can a variable be passed instead of a fixed name in a PHP script to retrieve values from a table column?

To pass a variable instead of a fixed name in a PHP script to retrieve values from a table column, you can use prepared statements in combination with placeholders. This allows you to dynamically bind variables to the query, making your code more secure and flexible. By using placeholders, you can easily substitute variable values in your SQL query without the risk of SQL injection.

// Assuming $columnName is the variable containing the column name
// Assuming $variable is the variable containing the value to retrieve

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

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

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

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

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

// Loop through the results
foreach ($results as $row) {
    // Do something with the data
}