0

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();
}
Jordan
  • 902
  • 2
  • 10
  • 37
  • 5
    did you enable exceptions in pdo? by default pdo fails by returning boolean false, and throws no exceptions. – Marc B Jul 19 '16 at 16:34
  • 1
    Side note, you don't have to terminate queries using `;` so get rid of that. Also, what @MarcB said - make sure you set PDO in exception mode first. – N.B. Jul 19 '16 at 16:36
  • @MarcB I did not. I wasn't even aware they had to be enabled. The PDO documentation is a pain.. – Jordan Jul 19 '16 at 16:55
  • only place pdo will throw an exception automatically is during the initial `new PDO(...)`. everything else defaults to return-false-on-failure unless you explicitly change it – Marc B Jul 19 '16 at 16:56
  • You can always use one of great libraries such as Doctrine, Eloquent or Propel and forget about fiddling with PDO, just focus on actual domain code. – N.B. Jul 19 '16 at 16:58

1 Answers1

1

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

Jordan
  • 902
  • 2
  • 10
  • 37