我在使用事务查询时遇到了一些麻烦。我有2张桌子, “科目”和链接表调用“tutorsubjects”。我使用的是MariaDB版本10.0.21。我创建了以下查询,但我不断收到“语法错误或访问冲突:1064”错误。
public function addSubject($values){
try {
$temp = $this->db->query("
BEGIN;
INSERT INTO subjects
(subject_code, subject_name, subject_grade, subject_description, subject_category)
VALUES (:subject_code, :subject_name, :subject_grade, :subject_description, :subject_category);
SET @last_id = LAST_INSERT_ID();
INSERT INTO tutorsubject
(tutor_id , subject_id)
VALUES (:tutor_id, @last_id);
COMMIT;",$values);
return $temp;
} catch (DBException $e) {
echo "Error:<br/>" . $e->getMessage();
return null;
} catch (Exception $e) {
echo "Error:<br/>" . $e->getMessage();
return null;
}
}
以下是解析为查询的值
$array = array("subject_code" => $code,
"subject_name" => $subject_name,
"subject_grade" => $grade,
"subject_description" => $subject_description,
"subject_category" => $subject_category,
"tutor_id"=>$selecttutor);
我收到以下错误:
SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法中有错误;查看与您的MariaDB服务器版本对应的手册,以便在''reach'附近使用正确的语法。'subject'('subject_code','subject_name','subject_grade','subject_de'在第1行 原始SQL:INSERT INTO'达到'。'subject'('subject_code','subject_name','subject_grade','subject_description','subject_category')VALUES(:subject_code,:subject_name,:subject_grade,:subject_description,:subject_category) ;
我的问题是,当我在phpMyAdmin中运行此查询时,它完成没有任何问题。我正在使用一个发现here的PDO MySQL类作为我的数据库交互的基础。我开始认为也许班级不直接支持交易?
任何想法都会非常感激。
答案 0 :(得分:0)
您应该尝试单独保留COMMIT
和BEGIN
个查询。
尝试:
// start the transaction
$this->db->query("BEGIN;");
//rest of your queries with db->query() go here
$this->db->query("INSERT INTO subjects
(subject_code, subject_name, subject_grade, subject_description, subject_category)
VALUES (:subject_code, :subject_name, :subject_grade, :subject_description, :subject_category);
SET @last_id = LAST_INSERT_ID();
INSERT INTO tutorsubject
(tutor_id , subject_id)
VALUES (:tutor_id, @last_id);");
//commit
$this->db->query("COMMIT;");
MySQL正在尝试将所有这些作为一个查询执行,并且它不会将整个命令识别为单独的查询。 PhpMyadmin自己将它们分开,这就是它们在那里正确运行的原因。
答案 1 :(得分:0)
有些东西是围绕数据库和表名添加撇号。这在语法上是错误的(除非你打开了某个ansi模式)。他们需要是支持者(`)。
答案 2 :(得分:0)
尝试让PHP完成工作+使用PDO事务方法,值部分未经测试,因此您需要确保其正确:
$this->db->beginTransaction();
$this->db->query("INSERT INTO subjects
(subject_code, subject_name, subject_grade, subject_description, subject_category)
VALUES (:subject_code, :subject_name, :subject_grade, :subject_description, :subject_category)", $values);
$values['last_id'] = $this->db->lastInsertId();
if (empty($values['last_id'])) {
$this->db->rollBack();
} else {
$this->db->query("INSERT INTO tutorsubject
(tutor_id , subject_id)
VALUES (:tutor_id, :last_id)", $values);
$this->db->commit();
}