当我尝试运行此代码时,它不会将数据插入数据库吗?
<?php
class Database {
private $dsn;
function __construct($dbname, $host, $user, $password, $enckey) {
$this->dsn = "mysql:dbname=" . $dbname . ';host=' . $host;
$this->user = $user;
$this->password = $password;
}
private function createDSN() {
return $this->dsn;
}
public function createConnection() {
try {
$dbh = new PDO(self::createDSN(), $this->user, $this->password);
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
return $dbh;
}
}
$db = new Database('mytest', 'localhost', 'root', 'hashedpassword', null);
$dbh = $db->createConnection();
$sql = $dbh->prepare("INSERT INTO contacts (firstname, lastname) VALUES (?,?)");
$sql->execute(array("abc", "xyz"));
?>
答案 0 :(得分:2)
我没有收到错误消息
但你必须得到它。向其他人询问您的数据库是没有意义的 询问数据库本身是一种更好的想法。
将此行添加到您的createConnection()(我不知道这个函数是什么,但是你已经拥有它)
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
以这种方式运行代码
try {
$sql = $dbh->prepare("INSERT INTO contacts (firstname, lastname) VALUES (?,?)");
$sql->execute(array("abc", "xyz"));
} catch (PDOException $e) {
echo $e->getMessage();
}