PHP MYSQL事务返回错误SQLSTATE [HY000]:一般错误

时间:2016-08-06 16:41:26

标签: php mysql pdo transactions

我收到了这段代码:

$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然后,我将代码减少到最小值以重现错误,但我可以&# 39;我想出来了,我认为它与功能的回归有关,但在手册中却说明了

  

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中,所以我想现在这个有效。

1 个答案:

答案 0 :(得分:0)

最佳解决方案是使用PDO tools for transactions。并从sql查询中删除BEGIN, COMMIT

关于PDOcommit() ...我认为您收到了错误,因为fetch()commit()之后调用了。这样没有错误:

$stmt = $this->con->beginTransaction();
$stmt = $this->con->prepare($qry);
$stmt->execute();

$result = $stmt->fetch(PDO::FETCH_ASSOC);

$this->con->commit();

return $result;

我希望这是你需要的。