当前位置:网站首页>PHP MySQL inserts multiple pieces of data
PHP MySQL inserts multiple pieces of data
2022-07-03 17:50:00 【Crooning ~ shallow singing】
Use MySQLi and PDO towards MySQL Insert multiple data
mysqli_multi_query() Function can be used to execute multiple SQL sentence .
The following example shows "MyGuests" Three new records have been added to the table :
example (MySQLi - object-oriented )
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // Create links $conn = new mysqli($servername, $username, $password, $dbname); // Check links if ($conn->connect_error) { die(" The connection fails : " . $conn->connect_error); } $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', '[email protected]');"; $sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', '[email protected]');"; $sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Julie', 'Dooley', '[email protected]')"; if ($conn->multi_query($sql) === TRUE) { echo " New record inserted successfully "; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?>
| Please note that , Every SQL Statements must be separated by semicolons . |
|---|
example (MySQLi - Process oriented )
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // Create links $conn = mysqli_connect($servername, $username, $password, $dbname); // Check links if (!$conn) { die(" The connection fails : " . mysqli_connect_error()); } $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', '[email protected]');"; $sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', '[email protected]');"; $sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Julie', 'Dooley', '[email protected]')"; if (mysqli_multi_query($conn, $sql)) { echo " New record inserted successfully "; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } mysqli_close($conn); ?>
example (PDO)
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDBPDO"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Start business $conn->beginTransaction(); // SQL sentence $conn->exec("INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', '[email protected]')"); $conn->exec("INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', '[email protected]')"); $conn->exec("INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Julie', 'Dooley', '[email protected]')"); // Commit transaction $conn->commit(); echo " New record inserted successfully "; } catch(PDOException $e) { // Rollback if execution fails $conn->rollback(); echo $sql . "<br>" . $e->getMessage(); } $conn = null; ?>
Use preprocessing statements
mysqli Extensions provide a second way to insert statements .
We can preprocess statements and bind parameters .
mysql Extensions can send statements or query to without data mysql database . You can relate to columns or " binding " Variable .
example (MySQLi Use preprocessing statements )
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Detection connection if ($conn->connect_error) { die(" The connection fails : " . $conn->connect_error); } else { $sql = "INSERT INTO MyGuests(firstname, lastname, email) VALUES(?, ?, ?)"; // by mysqli_stmt_prepare() initialization statement object $stmt = mysqli_stmt_init($conn); // Preprocessing statement if (mysqli_stmt_prepare($stmt, $sql)) { // Binding parameters mysqli_stmt_bind_param($stmt, 'sss', $firstname, $lastname, $email); // Set parameters and execute $firstname = 'John'; $lastname = 'Doe'; $email = '[email protected]'; mysqli_stmt_execute($stmt); $firstname = 'Mary'; $lastname = 'Moe'; $email = '[email protected]'; mysqli_stmt_execute($stmt); $firstname = 'Julie'; $lastname = 'Dooley'; $email = '[email protected]'; mysqli_stmt_execute($stmt); } } ?>
We can see that modularity is used to deal with the problem in the above example . We can make it easier to read and manage by creating code blocks .
Note the binding of parameters . Let's see mysqli_stmt_bind_param() The code in :
mysqli_stmt_bind_param($stmt, 'sss', $firstname, $lastname, $email);
This function binds the parameter query and passes the parameter to the database . The second parameter is "sss" . The following list shows the types of parameters . s Characters tell mysql The argument is a string .
It can be the following four parameters :
- i - Integers
- d - Double precision floating point
- s - character string
- b - Boolean value
Each parameter must specify the type , To ensure data security . Through type judgment, we can reduce SQL The risk of injecting vulnerabilities .
边栏推荐
- Graduation summary
- Applet setting multi account debugging
- Managing multiple selections with MVVM - managing multiple selections with MVVM
- Baiwen.com 7 days Internet of things smart home learning experience punch in the next day
- Leetcode 108 converts an ordered array into a binary search tree -- recursive method
- PUT vs. POST for Uploading Files - RESTful API to be Built Using Zend Framework
- link preload prefetch
- 互聯網醫院HIS管理平臺源碼,在線問診,預約掛號 智慧醫院小程序源碼
- Talk about the design and implementation logic of payment process
- 自动渗透测试工具核心功能简述
猜你喜欢

Baiwen.com 7 days Internet of things smart home learning experience punch in the next day

UE4 official charging resources, with a total price of several thousand

Qt调节Win屏幕亮度和声音大小

Select 3 fcpx plug-ins. Come and see if you like them

Investigation on the operation prospect of the global and Chinese Anti enkephalinase market and analysis report on the investment strategy of the 14th five year plan 2022-2028

聊聊支付流程的設計與實現邏輯

As soon as we enter "remote", we will never regret, and several people will be happy and several people will be sad| Community essay solicitation

Analysis report on production and marketing demand and investment forecast of China's PVC industry from 2021 to 2026

Golang单元测试、Mock测试以及基准测试

Vs2013 has blocked the installer, and ie10 needs to be installed
随机推荐
How to enforce parameters in PowerShell- How do I make parameters mandatory in PowerShell?
How to deploy applications on kubernetes cluster
BFS - topology sort
Ssl/bio of OpenSSL_ get_ fd
List的stream中Long对象与long判等问题记录
Global and Chinese health care OEM and ODM market status survey and investment planning recommendations report 2022-2028
PS screen printing brush 131, many illustrators have followed suit
Is AI too slow to design pictures and draw illustrations? 3 sets of practical brushes to save you
QT学习日记9——对话框
[UE4] brush Arctic pack high quality Arctic terrain pack
c# . Net tool ecosystem
TensorBoard快速入门(Pytorch使用TensorBoard)
Cloud primordial weekly | CNCF released the 2021 cloud primordial development status report, which was released on istio 1.13
UE4 official charging resources, with a total price of several thousand
Type conversion, variable
c# .net 工具生态
自动渗透测试工具核心功能简述
PUT vs. POST for Uploading Files - RESTful API to be Built Using Zend Framework
Five problems of database operation in commodity supermarket system
Baiwen.com 7 days Internet of things smart home learning experience punch in the next day
