What are the potential security risks associated with not properly escaping or encoding special characters in PHP when interacting with a database?
Failure to properly escape or encode special characters in PHP when interacting with a database can lead to SQL injection attacks, where malicious code is injected into SQL queries. This can result in unauthorized access to the database, data theft, and potentially the deletion or modification of sensitive information.
// Using prepared statements with PDO to properly escape special characters
$pdo = new PDO("mysql:host=localhost;dbname=myDB", "username", "password");
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();
$results = $stmt->fetchAll();