What common mistakes should be avoided when handling database queries and result sets in PHP scripts?
One common mistake to avoid when handling database queries and result sets in PHP scripts is not properly sanitizing user input, which can lead to SQL injection attacks. To prevent this, always use prepared statements with parameterized queries to safely execute SQL commands.
// Example of using prepared statements to prevent SQL injection
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL query with a placeholder for user input
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
// Bind the user input to the placeholder
$stmt->bindParam(':username', $_POST['username']);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();
// Display the results
foreach ($results as $row) {
echo $row['username'] . '<br>';
}