What are the potential security risks associated with using mysql_query() in PHP scripts?

When using mysql_query() in PHP scripts, there is a risk of SQL injection attacks if user input is not properly sanitized. To mitigate this risk, it is recommended to use prepared statements with parameterized queries instead. This helps prevent malicious SQL queries from being executed by treating user input as data rather than executable code.

// Using prepared statements with parameterized queries to prevent SQL injection

// Establish a connection to the database
$connection = new mysqli($host, $user, $password, $database);

// Prepare a SQL statement with a placeholder for the user input
$stmt = $connection->prepare("SELECT * FROM users WHERE username = ?");

// Bind the user input to the placeholder
$stmt->bind_param("s", $username);

// Set the user input
$username = $_POST['username'];

// Execute the query
$stmt->execute();

// Fetch the results
$result = $stmt->get_result();

// Process the results as needed
while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

// Close the statement and connection
$stmt->close();
$connection->close();