在SQL转换中,我得到了未捕获的PDO Exepction错误。

问题描述 投票:-1回答:1

这个代码。

$sql = '
    START TRANSACTION;
    INSERT INTO translation (lang, author, title, text)
      VALUES(:lang, :author, :title, :text);
    INSERT INTO article (translation, author, category, views, banner, visible) 
      VALUES(LAST_INSERT_ID(), :author, :category, 0, :banner, :visible);
    COMMIT;';


    $params = array("lang" => $lang, 
                    "author" => $author, 
                    "title" => $title, 
                    "text" => $content, 
                    "category" => $category, 
                    "banner" => $banner, 
                    "visible" => $v);


    $stmt = $conn->prepare($sql);
    $stmt->execute($params);

给我带来了这个错误。

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INSERT INTO translation (lang, author, title, text) VALUES(?, ?, ?, ?); ' at line 2 in C:\xampp\htdocs\admin\add-article.php:57 Stack trace: #0 C:\xampp\htdocs\admin\add-article.php(57): PDO->prepare('\r\n START TRA...') #1 {main} thrown in C:\xampp\htdocs\admin\add-article.php on line 57

这是我第一次尝试使用PDO交易。我直接在phpMyAdmin中尝试了这个SQL语句。

BEGIN;
    INSERT INTO translation (lang, author, title, text)
      VALUES(1, 2, "test", "test");
    INSERT INTO article (translation, author, category, views, banner, visible) 
      VALUES(LAST_INSERT_ID(), 2, 1, 100, "", 1);
COMMIT;

它工作了,但在php脚本中没有工作。 我写了'START TRANSACTION',是基于 此职位有什么想法吗?

php mysql pdo
1个回答
0
投票

你需要分别运行每个查询。

另外,通常一个事务是用try catch包装的。

 try {
    $pdo->beginTransaction();
    $sql = 'INSERT INTO translation (lang, author, title, text)
        VALUES(:lang, :author, :title, :text)';
    $params = array("lang" => $lang, 
                    "author" => $author, 
                    "title" => $title, 
                    "text" => $content, 
    );
    $stmt = $conn->prepare($sql);
    $stmt->execute($params);    

    $sql = 'INSERT INTO article (translation, author, category, views, banner, visible) 
        VALUES(LAST_INSERT_ID(), :author, :category, 0, :banner, :visible)';
    $params = array(
                    "author" => $author, 
                    "category" => $category, 
                    "banner" => $banner, 
                    "visible" => $v
    );
    $stmt = $conn->prepare($sql);
    $stmt->execute($params);    

    $pdo->commit();
}catch (Exception $e){
    $pdo->rollback();
    throw $e;
}
© www.soinside.com 2019 - 2024. All rights reserved.