当前位置:网站首页>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 .
边栏推荐
- How to purchase Google colab members in China
- [set theory] order relation: summary (partial order relation | partial order set | comparable | strictly less than | covering | hasto | total order relation | quasi order relation | partial order rela
- STM32实现74HC595控制
- (8) HS corner detection
- Write a program to process a list container of string type. Find a special value in the container 9.27: and delete it if found. Rewrite the above procedure with deque container.
- Micro service component sentinel console call
- 聊聊支付流程的設計與實現邏輯
- 自动渗透测试工具核心功能简述
- Gear2021 monthly update - December
- 问题随记 —— 在 edge 上看视频会绿屏
猜你喜欢

互联网医院HIS管理平台源码,在线问诊,预约挂号 智慧医院小程序源码

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

1146_ SiCp learning notes_ exponentiation

1147_ Makefile learning_ Target files and dependent files in makefile

微服务组件Sentinel控制台调用

IntelliJ 2021.3 short command line when running applications

MySQL grouping query

1164 Good in C

Global and Chinese health care OEM and ODM market status survey and investment planning recommendations report 2022-2028

Cloud primordial weekly | CNCF released the 2021 cloud primordial development status report, which was released on istio 1.13
随机推荐
小程序 多tab 多swiper + 每个tab分页
Where is the database account used when running SQL tasks in data warehouse tasks configured
Keepalived 设置不抢占资源
AcWing 4489. 最长子序列
Select 3 fcpx plug-ins. Come and see if you like them
Mathematical formula (test)
OpenSSL的SSL/BIO_get_fd
Golang单元测试、Mock测试以及基准测试
Research Report on investment trends and development planning of China's thermal insulation material industry, 2022-2028
Postfix 技巧和故障排除命令
Graduation summary
Life perception 1
Gear2021 monthly update - December
Kotlin's collaboration: Context
Where is the monitoring page of RDS database?
聊聊支付流程的设计与实现逻辑
STM32实现74HC595控制
UE4 official charging resources, with a total price of several thousand
Analyse ArrayList 3: suppression d'éléments
Market demand survey and marketing strategy analysis report of global and Chinese pet milk substitutes 2022-2028
