如何将多个查询更新为一个

时间:2013-07-25 08:40:44

标签: php mysql

这是mu查询

$sql_query= "insert into shortdb1.currency_code set currency_code = 'KWD', 
based_on = 'KWD', currency_rate = '1.00', 
last_update = '2013-07-25 11:41:33';
insert into shortdb1.currency set currency_code = 'KWD', 
language_code = 'EN', currency_name = 'Kuwaiti Dinar';";


    $conn_1->query($sql_query)

但我收到错误

您的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在第4行的insert into shortdb1.currency set currency_code = 'KWD', language_code = 'EN','附近使用正确的语法

4 个答案:

答案 0 :(得分:1)

您的查询需要存储为字符串,即:

$sql_query = insert into shortdb1.currency_code set currency_code = 'INR', based_on = 'KWD', currency_rate = '200', last_update = '2013-07-25 11:14:26';

需要

$sql_query = "insert into shortdb1.currency_code set currency_code = 'INR', based_on = 'KWD', currency_rate = '200', last_update = '2013-07-25 11:14:26'";

答案 1 :(得分:1)

在查询和php句子的末尾你缺少大量的引号和分号:

$sql_query = "insert into shortdb1.currency_code set currency_code = 'INR', based_on = 'KWD', currency_rate = '200', last_update = '2013-07-25 11:14:26';";

$sql_query .= "insert into shortdb1.currency set currency_code = 'INR', language_code = 'EN', currency_name = 'Indian Rupee', based_on = 'KWD', currency_rate = '200', last_update   = '2013-07-25 11:14:26';";

$conn_1->query($sql_query);

答案 2 :(得分:1)

如果要发送多个更新查询,可以使用事务

$firstQuery = "insert into shortdb1.currency_code set currency_code = 'KWD', based_on = 'KWD', currency_rate = '1.00', last_update = '2013-07-25 11:41:33'";
$secondQuery = "insert into shortdb1.currency set currency_code = 'KWD', language_code = 'EN', currency_name = 'Kuwaiti Dinar';";

try {
    // create transaction
    $conn->beginTransaction();

    // multiple query commands
    $conn->query($firstQuery);
    $conn->query($secondQuery);
    // ect...

    // if we are here, then the above query got passed correctly without exception
    // now we can commit the transaction
    $conn->commit();
} 
catch (Exception $e) {
    // if above commands fails, the db gets a rollback task
    $conn->rollback();
}

这是在一个序列中对数据库使用多个插入/更新查询的好方法。

事务的强大之处在于,您可以创建一个更新查询数组,并在上面的块中循环遍历该数组,而不是多行查询。

答案 3 :(得分:1)

我认为您的查询形成错误。 SET关键字用于UPDATE次查询。

对于INSERT查询,它应采用以下格式:

INSERT INTO TABLE_NAME (column1, column2, column3)  
                VALUES (value1, value2, value3);