在PHP中執行MySQL批處理可以通過使用mysqli
或PDO
擴展來實現。以下是一個簡單的示例代碼:
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();
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注入攻擊。