jeudi 6 septembre 2018

Nested if statement in PHP MySQL SELECT

I need to cross-reference rows. If the row does not exist, then insert it.

Here are the criterias it needs to go through before it can be inserted into database:

First find appointments that belong to the user (user_id).

Then find appointments that match the appointment ID (appointment_id). If appointment ID DOES NOT exist, continue to the next step.

If the appointment ID DOES NOT exist, then search if an appointment matches the appointment date AND time (appointment_date) (appointment_time).

If it DOES NOT exist, then INSERT into database.

Here is my code so far. How can I make my nested if statements of SELECT faster and more simpler?

// Search for appointment by appointment ID to see if it already exists
$stmt = $dbh->prepare("SELECT id FROM users WHERE user_id = :user_id AND appointment_id = :appointment_id LIMIT 1");
$stmt->bindParam(':user_id', $userId);
$stmt->bindParam(':appointment_id', $appointmentId);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);

// If appointment does not already exist, search for appointment by date and time
if(!$result) {
    $stmt = $dbh->prepare("SELECT id FROM users WHERE user_id = :user_id AND appointment_date = :appointment_date AND appointment_time = :appointment_time LIMIT 1");
    $stmt->bindParam(':user_id', $userId);
    $stmt->bindParam(':appointment_date', $appointmentDate);
    $stmt->bindParam(':appointment_time', $appointmentTime);
    $stmt->execute();
    $result2 = $stmt->fetch(PDO::FETCH_ASSOC);

    if(!$result2) {
        // If appointment does not already exist, insert into database:
        $stmt = $dbh->prepare("INSERT INTO...")
    }
}

How can i make this faster and simpler/shorter?

Aucun commentaire:

Enregistrer un commentaire