php增加多行資料的方法:1、建立一個PHP範例檔案;2、連接資料庫;3、透過mysqli_multi_query()函數執行多條SQL語句並使用INSERT語句向資料表增加多行數據即可。
本文操作環境:windows7系統、PHP7.1版、DELL G3電腦
php怎麼增加多行資料?
mysqli_multi_query() 函數可用於執行多條SQL語句。
以下實例為"MyGuests" 表新增了三個新的記錄:
實例(MySQLi - 物件導向)
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 创建链接 $conn = new mysqli($servername, $username, $password, $dbname); // 检查链接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com');"; $sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', 'mary@example.com');"; $sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Julie', 'Dooley', 'julie@example.com')"; if ($conn->multi_query($sql) === TRUE) { echo "新记录插入成功"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?>
Note 請注意,每個SQL語句必須使用分號隔開。
實例 (MySQLi - 面向過程)
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 创建链接 $conn = mysqli_connect($servername, $username, $password, $dbname); // 检查链接 if (!$conn) { die("连接失败: " . mysqli_connect_error()); } $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com');"; $sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', 'mary@example.com');"; $sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Julie', 'Dooley', 'julie@example.com')"; if (mysqli_multi_query($conn, $sql)) { echo "新记录插入成功"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } mysqli_close($conn); ?>
推薦學習:《PHP影片教學》
以上是php怎麼增加多行數據的詳細內容。更多資訊請關注PHP中文網其他相關文章!