What are the best practices for handling user input in PHP to prevent duplicate credit?

To prevent duplicate credit when handling user input in PHP, it is important to sanitize and validate the input data before processing it. One way to achieve this is by checking if the input data already exists in the database before inserting it. Additionally, using prepared statements with parameterized queries can help prevent SQL injection attacks.

// Assume $credit is the user input data

// Sanitize and validate the input data
$credit = filter_var($credit, FILTER_SANITIZE_NUMBER_INT);

// Check if the credit already exists in the database
$stmt = $pdo->prepare("SELECT * FROM credits WHERE credit = :credit");
$stmt->bindParam(':credit', $credit, PDO::PARAM_INT);
$stmt->execute();

if($stmt->rowCount() > 0){
    // Handle duplicate credit error
    echo "Error: Credit already exists.";
} else {
    // Proceed with inserting the credit into the database
    $stmt = $pdo->prepare("INSERT INTO credits (credit) VALUES (:credit)");
    $stmt->bindParam(':credit', $credit, PDO::PARAM_INT);
    $stmt->execute();
    echo "Credit inserted successfully.";
}