What potential security risks are associated with passing SQL queries via $_GET in PHP?

Passing SQL queries via $_GET in PHP can lead to SQL injection attacks, where malicious users can manipulate the query to access or modify sensitive data in the database. To mitigate this risk, it is important to sanitize and validate user input before using it in SQL queries. One way to do this is by using prepared statements with parameterized queries, which separate the SQL query logic from the user input.

// Using prepared statements to prevent SQL injection
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check if the parameter exists in $_GET
if(isset($_GET['user_id'])) {
    // Prepare a SQL query with a placeholder for the user input
    $stmt = $mysqli->prepare("SELECT * FROM users WHERE id = ?");
    
    // Bind the user input to the placeholder
    $stmt->bind_param("i", $_GET['user_id']);
    
    // Execute the query
    $stmt->execute();
    
    // Fetch the results
    $result = $stmt->get_result();
    
    // Process the results
    while($row = $result->fetch_assoc()) {
        // Do something with the data
    }
    
    // Close the statement
    $stmt->close();
}

// Close the database connection
$mysqli->close();