What are some best practices for handling and querying IDs in PHP?

When handling and querying IDs in PHP, it is important to validate and sanitize user input to prevent SQL injection attacks and ensure data integrity. One best practice is to use prepared statements with parameterized queries to safely handle IDs in database queries. Additionally, it is recommended to use integer casting or type checking to ensure that the ID is in the correct format before using it in database operations.

// Example of validating and sanitizing an ID before querying the database
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($id <= 0) {
    // Handle invalid ID input
    echo "Invalid ID";
} else {
    // Use prepared statement to query database with the sanitized ID
    $stmt = $pdo->prepare("SELECT * FROM table WHERE id = :id");
    $stmt->bindParam(':id', $id, PDO::PARAM_INT);
    $stmt->execute();
    $result = $stmt->fetch();
    
    // Process the query result
    if ($result) {
        // Do something with the data
    } else {
        // Handle ID not found in database
        echo "ID not found";
    }
}