[英]PHP MYSQL transaction returns error SQLSTATE[HY000]: General error
我得到了這段代碼:
$qry = "BEGIN; SELECT title FROM properties WHERE id=? LIMIT 1; COMMIT";
$arr = array(59);
$stmt = $data_users->default_query($qry, $arr);
print_r($stmt);
這是我的功能:
public function default_query($qry, $arr)
{
try {
$stmt = $this->con->prepare($qry);
$stmt->execute($arr);
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo $e->getMessage();
}
}
當我嘗試處理結果時它返回錯誤,但是,如果我直接在SQL上執行相同的查詢,我得到了這個結果:
標題
標題測試
這是渴望的結果,但我不能在我的應用程序上得到它。 但是,如果我將$ qry更改為:
//Remove the begin And Commit stuff;
$qry = "SELECT title FROM properties WHERE id=? LIMIT 1";
它工作,問題是我需要使用事務,因為我需要稍后做一些事情,在其他一些表上插入最后一個id,然后,我將代碼減少到最小值以重現錯誤,但我無法想象它out,我認為這與函數的返回有關,但在手冊上說
PDO :: FETCH_ASSOC:返回由結果集中返回的列名索引的數組
這就是我現在所需要的。 我使用錯誤的FETCH嗎? 提前致謝。
更新好的,我嘗試了這個新功能,現在我得到一個布爾結果
$qry = "SELECT title FROM properties WHERE id=59 LIMIT 1";
public function commit_query($qry){
try {
$stmt = $this->con->beginTransaction();
$stmt = $this->con->prepare($qry);
$stmt->execute();
$stmt = $this->con->commit();
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
$stmt = $this->con->rollback();
}
}
// I got this error which its OK according to this
成功時返回TRUE,失敗時返回FALSE。
Fatal error: Call to a member function fetch() on boolean in
無論如何在這里得到一個獲取結果?
又一次更新
好的,我現在有了這個功能:
public function commit_query_withId($qry,$arr,$multiqry){
try {
$stmt = $this->con->beginTransaction();
$stmt = $this->con->prepare($qry);
$stmt->execute($arr);
$lastId = $this->con->lastInsertId();
$stmt = $this->con->prepare($multiqry);
$stmt->execute();
$stmt = $this->con->commit();
return compact("lastId","stmt");
} catch (Exception $e) {
$stmt = $this->con->rollback();
}
}
我發送這些查詢:
//capturedby comes from an array ex:<select name="capturedby[]"
$elements = $_POST['capturedby'];
foreach ($elements as $x){
$sql[] = '(LAST_INSERT_ID(), '.$x.')';
}
$data_users=new database_data();
$qry = "INSERT INTO properties (title, ...)". "VALUES (:tit,...);";
$arr = array(':tit'=>$_POST['title'],...);
$multiqry='INSERT INTO captured_by (property_id, users_admin_id) VALUES '.implode(',', $sql);
$stmt=$data_users->commit_query_withId($qry,$arr,$multiqry);
if ($stmt["stmt"]==true) {
$data['valid'] = true;
$data['response'] = $msg_echo->messages('3');
$data['id'] = $stmt['lastId'];
}else{
$data['valid'] = false;
$data['response'] = $msg_echo->messages('4');
}
現在我有2個成功的插入和最后一個插入的id在$ var中,所以我想這現在適用。
最好的解決方案是使用PDO工具進行交易 。 並從sql查詢中刪除BEGIN, COMMIT
。
關於PDO
和commit()
...我認為你得到了錯誤,因為在commit()
之后調用了fetch()
commit()
。 這樣沒有錯誤:
$stmt = $this->con->beginTransaction();
$stmt = $this->con->prepare($qry);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$this->con->commit();
return $result;
我希望這就是你所需要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.