What are best practices for preventing SQL injection when using $_GET in PHP?

SQL injection can be prevented when using $_GET in PHP by properly sanitizing and validating user input before using it in SQL queries. One way to do this is by using prepared statements with parameterized queries to separate the SQL logic from the user input. This helps prevent malicious SQL code from being executed.

// Example of preventing SQL injection with $_GET in PHP
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check if the id parameter is set in the $_GET array
if(isset($_GET['id'])){
    // Sanitize the input to prevent SQL injection
    $id = $mysqli->real_escape_string($_GET['id']);

    // Prepare a SQL statement using a parameterized query
    $stmt = $mysqli->prepare("SELECT * FROM users WHERE id = ?");
    
    // Bind the parameter to the statement
    $stmt->bind_param("i", $id);
    
    // Execute the statement
    $stmt->execute();
    
    // Get the result set
    $result = $stmt->get_result();
    
    // Fetch the data
    while($row = $result->fetch_assoc()){
        // Output the data
        echo "User ID: " . $row['id'] . " - Name: " . $row['name'] . "<br>";
    }
    
    // Close the statement
    $stmt->close();
}