Is there a more secure alternative to addslashes for preventing SQL injection in PHP?

The issue with using addslashes to prevent SQL injection in PHP is that it is not foolproof and can still leave vulnerabilities in the code. A more secure alternative is to use prepared statements with parameterized queries. This method separates the SQL query logic from the data being passed into it, effectively preventing SQL injection attacks.

// Establish a connection to the database
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind the parameter value to the query
$stmt->bindParam(':username', $username);

// Execute the query
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll();