Why is it important to use prepared statements in MySQLi or PDO instead of escaping functions like mysql_real_escape_string?

Using prepared statements in MySQLi or PDO is important because it helps prevent SQL injection attacks by separating SQL logic from user input. This method ensures that input data is treated as data, not as SQL commands. Prepared statements also provide better performance as the query is parsed only once and executed multiple times with different parameters.

// Example of using prepared statements in PDO
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();

// Example of using prepared statements in MySQLi
$mysqli = new mysqli("localhost", "username", "password", "mydatabase");

$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param('s', $username);
$stmt->execute();