What are the differences between using the mysql_query() function and prepared statements in PHP for database interactions?

When interacting with a database in PHP, using prepared statements is considered more secure and efficient compared to using the mysql_query() function. Prepared statements help prevent SQL injection attacks by separating SQL logic from user input. They also improve performance by allowing the database to compile the query once and execute it multiple times with different parameters.

// Using prepared statements for database interactions
$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();

while ($row = $stmt->fetch()) {
    // Process the fetched data
}