在php中使用临时表执行多个查询

时间:2014-02-17 12:19:55

标签: php mysql sql

我有以下查询,要复制表中的行并更改几列。

CREATE TEMPORARY TABLE temp_table AS 
       SELECT * 
         FROM table1 
        WHERE offertecode = '1c12a23453453458e492230df420972'; 

UPDATE temp_table 
   SET offertecode = '82a24c7da2342423424351804ab043', 
       id = NULL, 
       reference = '[COPY] subject'; 

INSERT INTO table1 
       SELECT * 
         FROM temp_table; 

DROP TEMPORARY TABLE temp_table;

这在phpmyadmin中工作得非常好,但我无法在PHP中使用它,我收到错误:

You have an error in your SQL syntax; 
check the manual that corresponds to your MySQL server version for the right syntax 
to use near 'UPDATE temp_table SET offertecode = '82a24c7da2342423424351804ab043', 
id = ' at line 5

有人可以帮我解决如何在PHP中执行此查询的问题吗?

PHP代码:

$mysqli->query("CREATE TEMPORARY TABLE temp_table AS 
           SELECT * 
             FROM table1 
            WHERE offertecode = '1c12a23453453458e492230df420972'; 

UPDATE temp_table 
   SET offertecode = '82a24c7da2342423424351804ab043', 
       id = NULL, 
       reference = '[COPY] subject'; 

INSERT INTO table1 
       SELECT * 
         FROM temp_table; 

DROP TEMPORARY TABLE temp_table;");

谢谢!

2 个答案:

答案 0 :(得分:0)

这不解决mysqli问题(在单个查询中有四个语句)。你应该单独运行它们。但是,你不需要四个陈述。只是做:

insert into table1(offertecode, id, reference, <rest of columns>)
    select '82a24c7da2342423424351804ab043' as offertecode, NULL as id, '[COPY] subject' as reference,
           <rest of columns>
    from table1
    where offertecode = '1c12a23453453458e492230df420972';

insert . . . select语句可以引用两个部分中的同一个表。即使在MySQL中。

答案 1 :(得分:0)

您需要使用$ mysqli-&gt; multi_query。基本答案是您无法使用$ mysqli-&gt;查询运行多个查询。语法错误是由于第二个查询试图在$ mysqli-&gt;查询下运行,该查询只允许一个主查询。该查询可以包含子查询或嵌套查询,但只能包含一个主查询。要运行多个查询,您必须使用$ mysqli-&gt; multi_query