What best practices should be followed when fetching data from a database in PHP?
When fetching data from a database in PHP, it is important to use prepared statements to prevent SQL injection attacks. Additionally, it is recommended to handle errors properly to ensure the stability of the application. Finally, it is good practice to close the database connection after fetching the data to free up resources.
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a SQL statement using a prepared statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
// Fetch the data
$user = $stmt->fetch();
// Close the database connection
$pdo = null;