阅读量:0
在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注入攻击。