当前位置:网站首页>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 .
边栏推荐
- What is the difference between cloud server and cloud virtual machine
- Remote office tools sharing | community essay solicitation
- Wechat applet for the first time
- [combinatorics] generating function (linear property | product property)
- UE4 official charging resources, with a total price of several thousand
- Research Report on investment trends and development planning of China's thermal insulation material industry, 2022-2028
- 问题随记 —— 在 edge 上看视频会绿屏
- Embedded-c language-7
- [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
- AcWing 4489. 最长子序列
猜你喜欢
国内如何购买Google Colab会员
Golang unit test, mock test and benchmark test
Research on Swift
Type conversion, variable
QT learning diary 9 - dialog box
基于人脸识别的课堂考勤系统 tkinter+openpyxl+face_recognition
[UE4] brush Arctic pack high quality Arctic terrain pack
TensorBoard快速入门(Pytorch使用TensorBoard)
STM32实现74HC595控制
Micro service component sentinel console call
随机推荐
vs2013已阻止安装程序,需安装IE10
微服务组件Sentinel控制台调用
How to read the source code [debug and observe the source code]
Draw some simple graphics with MFC
[combinatorics] generating function (summation property)
[vscode] convert tabs to spaces
Play with fancy special effects. This AE super kit is for you
Talk about the design and implementation logic of payment process
VM11289 WAService. js:2 Do not have __ e handler in component:
ArrayList分析3 : 删除元素
Kubernetes resource object introduction and common commands (V) - (NFS & PV & PVC)
1147_ Makefile learning_ Target files and dependent files in makefile
[combinatorics] recursive equation (special solution example 1 Hannover tower complete solution process | special solution example 2 special solution processing when the characteristic root is 1)
Fedora 21 installs lamp host server
Micro service component sentinel console call
Basic grammar of interview (Part 2)
TCP congestion control details | 3 design space
How to purchase Google colab members in China
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
PHP returns 500 errors but no error log - PHP return 500 error but no error log