How can the use of mysql_query() function in PHP be improved to prevent SQL injection attacks?

To prevent SQL injection attacks when using the mysql_query() function in PHP, it is recommended to use prepared statements with parameterized queries. This helps sanitize user input and prevents malicious SQL queries from being executed.

// Establish a connection to the MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Check if the connection was successful
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Prepare a SQL statement using a parameterized query
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = mysqli_prepare($connection, $sql);

// Bind parameters and execute the statement
$username = $_POST['username'];
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);

// Fetch results
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
    // Process results
}

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