What are the advantages of using PHP functions like mysql_query() for database interactions, and what are the recommended alternatives for improved security and performance?
When using PHP functions like `mysql_query()` for database interactions, there is a risk of SQL injection attacks due to lack of input validation and escaping. To improve security and performance, it is recommended to use prepared statements with parameterized queries or an ORM (Object-Relational Mapping) library like PDO or mysqli.
// Using prepared statements with PDO for improved security and performance
$pdo = new PDO("mysql:host=localhost;dbname=myDB", "username", "password");
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
// Fetch data
while ($row = $stmt->fetch()) {
// Process data
}