What alternative functions or methods can be used in PHP to prevent SQL injection besides addslashes()?
SQL injection can be prevented in PHP by using prepared statements with parameterized queries. This method separates the SQL query logic from the user input, effectively preventing malicious SQL injection attacks. Prepared statements ensure that input values are treated as data and not executable SQL code.
// Using prepared statements to prevent SQL injection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();