How can PDO be utilized to create an array for a database query in PHP?

To create an array for a database query using PDO in PHP, you can use prepared statements to bind parameters dynamically. This allows you to safely pass user input to the query without risking SQL injection attacks. By utilizing PDO's prepared statements and parameter binding, you can create a secure and efficient way to interact with your database.

// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a statement with a placeholder for the parameter
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');

// Bind the parameter to the placeholder
$id = 1;
$stmt->bindParam(':id', $id, PDO::PARAM_INT);

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

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

// Output the results
print_r($results);