当前位置:网站首页>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 .
边栏推荐
- Records of long objects and long judgments in the stream of list
- Discussion sur la logique de conception et de mise en oeuvre du processus de paiement
- AcWing 4489. Longest subsequence
- Analysis report on production and marketing demand and investment forecast of China's PVC industry from 2021 to 2026
- Implementation of Tetris in C language
- 小程序 多tab 多swiper + 每个tab分页
- Analyse ArrayList 3: suppression d'éléments
- [combinatorics] generating function (linear property | product property)
- Hongmeng fourth training
- c# . Net tool ecosystem
猜你喜欢

Research Report on competitive strategy Outlook Analysis and investment strategic planning of China's smart home equipment industry, 2022-2028

Research on Swift

Hongmeng fourth training

1146_ SiCp learning notes_ exponentiation

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

聊聊支付流程的設計與實現邏輯
![How to read the source code [debug and observe the source code]](/img/40/a2fca67bcde3c468a739c6990325f4.jpg)
How to read the source code [debug and observe the source code]

1147_ Makefile learning_ Target files and dependent files in makefile
![[combinatorics] recursive equation (summary of the solution process of recursive equation | homogeneous | double root | non-homogeneous | characteristic root is 1 | exponential form | the bottom is th](/img/f1/c96c4a6d34e1ae971f492f4aed5a93.jpg)
[combinatorics] recursive equation (summary of the solution process of recursive equation | homogeneous | double root | non-homogeneous | characteristic root is 1 | exponential form | the bottom is th

Play with fancy special effects. This AE super kit is for you
随机推荐
Research Report on market demand and investment planning for the development of China's office chair industry, 2022-2028
Leetcode Valentine's Day Special - looking for a single dog
Micro service component sentinel console call
Getting started with deops
企业级自定义表单引擎解决方案(十一)--表单规则引擎1
PUT vs. POST for Uploading Files - RESTful API to be Built Using Zend Framework
Comparison of kotlin collaboration + retro build network request schemes
Discussion sur la logique de conception et de mise en oeuvre du processus de paiement
Select 3 fcpx plug-ins. Come and see if you like them
Web-ui automated testing - the most complete element positioning method
Leetcode 669 pruning binary search tree -- recursive method and iterative method
QT adjust win screen brightness and sound size
Is AI too slow to design pictures and draw illustrations? 3 sets of practical brushes to save you
MySQL grouping query
Introduction to SolidWorks gear design software tool geartrax
QT学习日记9——对话框
[combinatorics] generating function (shift property)
[combinatorics] recursive equation (summary of the solution process of recursive equation | homogeneous | double root | non-homogeneous | characteristic root is 1 | exponential form | the bottom is th
Golang unit test, mock test and benchmark test
[Yu Yue education] family education SPOC class 2 reference materials of Shanghai Normal University
