温馨提示×

如何在PHP中执行MySQL批处理

小樊
84
2024-07-24 09:35:12
栏目: 云计算

在PHP中执行MySQL批处理可以通过使用mysqliPDO扩展来实现。以下是一个简单的示例代码:

  1. 使用mysqli扩展执行MySQL批处理:
$mysqli = new mysqli('localhost', 'username', 'password', 'database');

$query = "
    INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2');
    INSERT INTO table_name (column1, column2) VALUES ('value3', 'value4');
    INSERT INTO table_name (column1, column2) VALUES ('value5', 'value6');
";

if ($mysqli->multi_query($query)) {
    do {
        if ($result = $mysqli->store_result()) {
            $result->free();
        }
    } while ($mysqli->next_result());
} else {
    echo "Error: " . $mysqli->error;
}

$mysqli->close();
  1. 使用PDO扩展执行MySQL批处理:
$dsn = 'mysql:host=localhost;dbname=database';
$username = 'username';
$password = 'password';

try {
    $pdo = new PDO($dsn, $username, $password);
    
    $query = "
        INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2');
        INSERT INTO table_name (column1, column2) VALUES ('value3', 'value4');
        INSERT INTO table_name (column1, column2) VALUES ('value5', 'value6');
    ";

    $stmt = $pdo->prepare($query);
    $stmt->execute();

    echo "Batch query executed successfully";
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}

在执行MySQL批处理时,请确保SQL语句正确并且安全,以防止SQL注入攻击。

0