我最近搬到了MariaDB,因为自从MySQL 5.6以来它已经失败了很多。
MariaDB运行完美,但在新项目中,我无法使用PHP脚本将数据插入数据库。我只能手动插入。我没有对使用MySQL的脚本做任何改动。
INSERT语句是:
INSERT INTO participantes (nome, curso, email, equipe) VALUES (:nome, :curso, :email, :equipe);
应该插入的脚本是:
$stmt = $this->dbh->prepare($this->SQL_INSERT);
$nome = $participante->nome();
$curso = $participante->curso();
$email = $participante->email();
$equipe = $participante->equipe();
$stmt->bindParam(':nome', $nome);
$stmt->bindParam(':curso', $curso);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':equipe', $equipe);
$stmt->execute();
“participante”函数返回要使用的数据,没有任何问题。一切都在try / catch块中,没有异常报告。
我的PDO课程如下:
class Connection extends PDO {
private $dsn = 'mysql:host=localhost;port=3307;dbname=dacu';
private $usr = 'dacu';
private $pwd = 'my password';
public $handle = null;
function __construct() {
try {
if ($this->handle == null) {
$dbh = new PDO($this->dsn, $this->usr, $this->pwd);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->handle = $dbh;
return $this->handle;
}
}
catch (PDOException $e) {
throw new Exception('Não foi possível conectar-se ao banco de dados: ' . $e->getMessage());
}
catch (Exception $e) {
throw new Exception('Um erro não identificado ocorreu: ' . $e->getMessage());
}
}
}
使用controller-> insert给我:
Warning: PDO::prepare(): SQLSTATE[00000]: No error: PDO constructor was not called in C:\Webserver\Files\dacu\controller\EquipesController.php on line 25
如果需要,我可以在pastebin上发布代码,只需询问。
答案 0 :(得分:1)
检查你的连接,然后尝试这种方式,它的工作正常:
//first you need a connection to mysql use this and replace the variables
try {
$dbh = new PDO('mysql:host=localhost;dbname='.$db_name.'', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
//then do the insert variable
$sql = 'INSERT INTO encomendas (`nome`, `user`, `id`, `email`) ';
$sql .= 'VALUES (:nome, :curso, :email, :equipe )';
$query = $dbh->prepare($sql);
//bindParam with your own variables
$query->bindParam(':nome', $varDoNome, PDO::PARAM_STR);
$query->bindParam(':curso', $varDoCurso, PDO::PARAM_STR);
$query->bindParam(':email', $varDoEmail, PDO::PARAM_STR);
$query->bindParam(':equipe', $varDaequipe, PDO::PARAM_STR);
//execute query
$query->execute()
;