如何在单个查询中运行多个查询?

时间:2014-07-01 13:04:14

标签: php mysql sql mysqli

DELETE FROM Table WHERE TableR = '1';
INSERT INTO Table (TableR, Seet, Keyword) VALUES ('1', '1', 'test1');
INSERT INTO Table (TableR, Seet, Keyword) VALUES ('1', '2', 'test2');
INSERT INTO Table (TableR, Seet, Keyword) VALUES ('1', '3', 'test3');

对于连接,我们使用代码:

$mysqli = new mysqli($this->MysqlHost,$this->MysqlUser,$this->MysqlPassword,$this->MysqlDatabase);
$result = $mysqli->query("SET NAMES utf8");
$result = $mysqli->query("set character_set_client='utf8'");
$result = $mysqli->query("set collation_connection='utf8_general_ci'");
$result = $mysqli->query($query);

现在我们需要使用多个查询来运行所有查询。

但我想只运行一个查询,即:

$query = "
        DELETE FROM Table WHERE TableR = '1';
        INSERT INTO Table (TableR, Seet, Keyword) VALUES ('1', '1', 'test1');
        INSERT INTO Table (TableR, Seet, Keyword) VALUES ('1', '2', 'test2');
        INSERT INTO Table (TableR, Seet, Keyword) VALUES ('1', '3', 'test3');
    ";

请告诉我如何在一个查询中运行多个查询?

3 个答案:

答案 0 :(得分:1)

使用多重查询?

您可以查看以下文档:

http://php.net/manual/en/mysqli.multi-query.php

如果您尝试插入多行,可以查看:

Batch insertion of data to MySQL database using php

(寻找LOAD DATA INFILE解决方案......)

答案 1 :(得分:1)

$result = $mysqli->multi_query($query);

享受!

答案 2 :(得分:0)

我希望这可以帮到你:http://www.php.net/manual/en/mysqli.quickstart.multiple-statement.php

如果您使用它,请注意安全性。

示例#1多个语句

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$sql = "SELECT COUNT(*) AS _num FROM test; ";
$sql.= "INSERT INTO test(id) VALUES (1); ";
$sql.= "SELECT COUNT(*) AS _num FROM test; ";

if (!$mysqli->multi_query($sql)) {
    echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

do {
    if ($res = $mysqli->store_result()) {
        var_dump($res->fetch_all(MYSQLI_ASSOC));
        $res->free();
    }
} while ($mysqli->more_results() && $mysqli->next_result());
?>

输出:

array(1) {
  [0]=>
  array(1) {
    ["_num"]=>
    string(1) "0"
  }
}
array(1) {
  [0]=>
  array(1) {
    ["_num"]=>
    string(1) "1"
  }
}