将数据插入多个表时出现SQL语法错误

时间:2018-07-09 07:24:30

标签: mysql sql sql-insert

我正在尝试在BEGIN;COMMIT;之间使用两个插入查询将数据插入到多个表中,但出现如下语法错误:

  

您的SQL语法有错误;似乎出现了错误:“在第2行插入INSTO INTO公司(名称,街道,邮编,地点,电话”

这是我的查询

BEGIN;
INSERT INTO company (name, street, zip, place, phone, contact, email, logo)
  VALUES('".$name."', '".$street."', '".$zip."', '".$place."', '".$phone."', '".$contact."', '".$email."', '".$file."');
INSERT INTO users (username, password)
  VALUES('".$username."', '".$pass."');
COMMIT;

我不确定错误在哪里。

我的PHP查询(在注释中要求):

$addcompany = "
    BEGIN;
  INSERT INTO company (name, street, zip, place, phone, contact, email, logo)
      VALUES('".$name."', '".$street."', '".$zip."', '".$place."', '".$phone."', '".$contact."', '".$email."', '".$file."');
  INSERT INTO users (username, password)
      VALUES('".$username."', '".$pass."');
  COMMIT;";
  $addcompany = $conn->query($addcompany);

在回应我的查询时:

BEGIN;
INSERT INTO company (name, street, zip, place, phone, contact, email, logo)
VALUES('test', 'test street 123', '3235DE', 'Rotterdam', '2356235235', 'testcontact', 'test@test.nl', '/home/website/public_html/logos/test.jpg');
INSERT INTO users (username, password)
VALUES('testuser', '$2y$10$M2vO60OuvmNxsmzbCIGhB.4EgQ55Qid/DPGAC3BYs/I2Twj8Afo5q');
COMMIT;

3 个答案:

答案 0 :(得分:1)

对于PHP变量,您需要转义符'才能将值视为字符串,请在执行它之前先通过传递sql参数和print @sql进行尝试

$addcompany = 
    'BEGIN
  INSERT INTO company (name, street, zip, place, phone, contact, email, logo)
      VALUES( '''+ ".$name." +''', '''+".$street."+''', '''+".$zip."+''', 
              '''+".$place."+''', '''+".$phone."+''', '''+".$contact."+''', 
              '''+".$email."+''', '''+".$file."+''');
  INSERT INTO users (username, password)
      VALUES('''+".$username."+''', '''+".$pass."+''');
  COMMIT'
  $addcompany = $conn->query($addcompany);

答案 1 :(得分:1)

似乎$ conn-> query()仅支持单个查询。 multi_query()是您可以尝试的一种方法。我在这里找到了:https://www.w3schools.com/php/php_mysql_insert_multiple.asp

答案 2 :(得分:-2)

将多个记录插入表中的sql语法如下,

INSERT INTO MyTable (Column1, Column2) VALUES(Value1, Value2), (Value1, Value2)

尝试