我试图通过事务声明插入两个插入int,但它不起作用。控制台给我数据库错误。我查看了文档http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers,很明显我遗漏了一些东西。
目标只是将两个不同的表插入不同的信息。我尝试了以下方法:
// create record
function create(){
try {
$stmt->beginTransaction();
$query = "INSERT INTO " . $this->table_name . "
SET user_id = ?, ";
// prepare query statement
$stmt = $this->conn->prepare($query);
// bind values to be inserted
$stmt->bindParam(1, $this->user_id);
$stmt->execute();
$query2 = "INSERT INTO legalcases_report
SET user_id = ?, ";
// prepare query statement 2
$stmt = $this->conn->prepare($query2);
$stmt->bindParam(1, $this->user_id);
$stmt->execute();
$stmt->commit();
return true;
} catch (Exception) {
$stmt->rollBack();
return false;
}
}
答案 0 :(得分:0)
此代码中存在许多问题,我希望我能抓住它们
// create record
function create(){
try {
// transaction work on a connection and not a statement
//$stmt->beginTransaction();
$this->conn->beginTransaction();
// Incorrect syntax for an INSERT command
// Error - Trailing comma in sytax
$query = "INSERT INTO " . $this->table_name . "
SET user_id = ?, ";
// prepare query statement
$stmt = $this->conn->prepare($query);
// bind values to be inserted
$stmt->bindParam(1, $this->user_id);
$stmt->execute();
// Incorrect syntax for an INSERT command
// Error - Trailing comma in sytax
$query2 = "INSERT INTO legalcases_report
SET user_id = ?, ";
// prepare query statement 2
$stmt = $this->conn->prepare($query2);
$stmt->bindParam(1, $this->user_id);
$stmt->execute();
// commit also works on a connection object
//$stmt->commit();
$this->conn->commit();
return true;
// PDO generates a PDOException so you should really catch that,
// it will fallback to the parent Exception object, BUT
// there may be times when you want to catch them seperately
// from the same try block, so use the correct one or both
} catch (PDOException $pex) {
$this->con->rollback();
$pex->getMessage();
exit; // because you have a serious problem
// or throw your own exception to the calling code
throw new Exception('Create user failed ' . $pex->getMessage());
}
}
答案 1 :(得分:-1)
我猜你应该使用PDO对象,而不是PDOStatement:
try {
$this->conn->beginTransaction();
...
$this->conn->commit();