What is the best practice for storing the result of a SQL query in a variable in PHP?

When storing the result of a SQL query in a variable in PHP, it is best practice to use prepared statements to prevent SQL injection attacks and ensure data security. Prepared statements separate SQL logic from user input, making it safer to execute queries. By using prepared statements, you can bind parameters and retrieve results securely.

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

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

// Bind a parameter to the prepared statement
$value = 'example';
$stmt->bindParam(':value', $value);

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

// Store the result in a variable
$result = $stmt->fetchAll();

// Use the result as needed
foreach ($result as $row) {
    echo $row['column_name'] . "<br>";
}