0

I'm trying to understand PDO prepared statements. Did I implement them correctly in the code below?

$guestFirstName = $_POST['guestFirstName'];
$guestLastName = $_POST['guestLastName'];
$guestMessage = $_POST['guestMessage'];

//remove whitespace from beginning and end
$guestName = trim($guestName);
$guestMessage = trim($guestMessage);

$errors = validate_inputs($guestFirstName, $guestLastName, $guestMessage);
//if there are no errors received.
    if (empty($errors)) {
      try {
        //open the database
        $db = new PDO(DB_PATH, DB_LOGIN, DB_PW);
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        //insert the first name, last name, and message into the database
        $stmt = $db->prepare("INSERT INTO guest_users(first, last) VALUES(:f,:l);");
        $stmt->bindParam('f', $guestFirstName);
        $stmt->bindParam('l', $guestLastName);
        $stmt->execute();

        $insertID = $db->lastInsertId();
      
       $stmt2 = $db->prepare("INSERT INTO guest_message (comment, user_id, date_sent) VALUES (:m,:i, now());");
       $stmt2->bindParam('m', $guestMessage);
       $stmt2->bindParam('i', $insertID);
       $stmt2->execute();

        $displayName = $db->query("SELECT * FROM guest_users where id = '$insertID'")->fetch(PDO::FETCH_ASSOC);
        $displayMessage = $db->query("SELECT * FROM guest_message where id = '$insertID'")->fetch(PDO::FETCH_ASSOC);

Below this is just HTML code where I'm inserting variables like $displayName['first'], $displayMessage['message'], etc. To display information from the database.

briann
  • 143
  • 7

0 Answers0