What are some potential security risks associated with using mysql_query in PHP?

Using mysql_query in PHP can lead to SQL injection attacks if user input is not properly sanitized. To mitigate this risk, it is recommended to use parameterized queries or prepared statements instead, as they automatically escape user input. This helps prevent malicious SQL code from being injected into the query.

// Using prepared statements to prevent SQL injection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Prepare a statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

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

// Get result
$result = $stmt->get_result();

// Fetch data
while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

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