PDO准备的声明什么都不做

时间:2016-07-19 16:29:20

标签: php mysql pdo

我正在尝试使用PDO和预准备语句进行简单插入,但它不会插入数据,返回错误或其他任何内容。日志也是空的。这是正在执行但什么都不做的代码。值不为空。

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();
}

奇怪的是,这段代码运行正常,它在每个请求的前一个代码之前执行:

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();
}

1 个答案:

答案 0 :(得分:1)

正如MarcB在评论中指出的那样,我没有在PDO中启用例外。在实例化PDO实例后使用db_handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);显示查询出错。

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