Home > Article > Backend Development > How to add multiple rows of data in php
php method to add multiple rows of data: 1. Create a PHP sample file; 2. Connect to the database; 3. Execute multiple SQL statements through the mysqli_multi_query() function and use the INSERT statement to add multiple rows to the data table. Just data.
The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer
How to add multiple rows of data in php?
mysqli_multi_query() function can be used to execute multiple SQL statements.
The following example adds three new records to the "MyGuests" table:
Example (MySQLi - Object-oriented)
<?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 Please note that each SQL statement must be separated by semicolons.
Example (MySQLi - process-oriented)
<?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); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to add multiple rows of data in php. For more information, please follow other related articles on the PHP Chinese website!