What are the best practices for handling database queries and outputting results in PHP?
When handling database queries in PHP, it is important to properly sanitize user input to prevent SQL injection attacks. Additionally, using prepared statements can help improve performance and security by separating the query logic from the data. Finally, carefully handle and output query results to ensure data integrity and prevent potential security vulnerabilities.
// Example of handling a database query with prepared statements
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a SQL query
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
// Bind parameters
$stmt->bindParam(':id', $userId, PDO::PARAM_INT);
// Execute the query
$stmt->execute();
// Fetch results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Output results
foreach ($results as $row) {
echo $row['username'] . "<br>";
}