简体   繁体   中英

PDO prepared statement does nothing

I am trying to do a simple insert using PDO and a prepared statement but it doesn't insert the data, return an error, or anything. The logs are empty as well. Here is the code that is getting executed but doing nothing. The values are not null.

try {
  $query = $this->db_handler->prepare('INSERT INTO submissions (firstname, lastname, email, phone, mailinglist) VALUES (:firstname, :lastname, :email, :phone, :mailinglist);');
  $query->bindParam(':firstname', $values['firstname']);
  $query->bindParam(':lastname', $values['lastname']);
  $query->bindParam(':email', $values['email']);
  $query->bindParam(':phone', $values['phone']);
  $query->bindParam(':mailinglist', $values['mailinglist']);
  $query->execute();
} catch (PDOException $e) {
  echo "DB error: " . $e->getMessage();
}

Weirdly, this code is working fine, which is being executed right before the previous code on every request:

try {
  $this->exec("CREATE DATABASE IF NOT EXISTS $this->db_name;");
  $this->exec("USE $this->db_name;");
  $this->exec("CREATE TABLE IF NOT EXISTS $this->table_name (
    id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    firstname VARCHAR(50) NOT NULL,
    lastname VARCHAR(50) NOT NULL,
    email VARCHAR(50) NOT NULL,
    phone VARCHAR(12) NOT NULL,
    mailinglist BOOLEAN NOT NULL,
    submitdate TIMESTAMP
  );");
} catch (PDOException $e) {
  echo "DB error: " . $e->getMessage();
}

As MarcB pointed out in the comments, I had not been enabling exceptions in PDO. Using db_handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); after instantiating a PDO instance showed that there was an error with the query.

http://php.net/manual/en/pdo.error-handling.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM