如何在PHP中执行MySQL批处理

avatar
作者
猴君
阅读量:0

在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注入攻击。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!