What potential pitfalls should be considered when using the mysql_query function in PHP for database operations?

One potential pitfall when using the mysql_query function in PHP is the risk of SQL injection attacks if user input is not properly sanitized. To prevent this, it is important to use parameterized queries or prepared statements instead. This helps to separate SQL code from user input, making it safer and more secure.

// Connect to the database
$conn = mysqli_connect("localhost", "username", "password", "database");

// Prepare a statement
$stmt = mysqli_prepare($conn, "SELECT * FROM users WHERE username = ?");

// Bind parameters
mysqli_stmt_bind_param($stmt, "s", $username);

// Set parameters and execute
$username = $_POST['username'];
mysqli_stmt_execute($stmt);

// Get results
$result = mysqli_stmt_get_result($stmt);

// Process results
while ($row = mysqli_fetch_assoc($result)) {
    // Do something with the data
}

// Close statement and connection
mysqli_stmt_close($stmt);
mysqli_close($conn);