15158846557 在线咨询 在线咨询
15158846557 在线咨询
所在位置: 首页 > 营销资讯 > 网站运营 > 插入多条数据-网站建设-微信广告

插入多条数据-网站建设-微信广告

时间:2023-08-08 14:54:02 | 来源:网站运营

时间:2023-08-08 14:54:02 来源:网站运营

插入多条数据-网站建设-微信广告:插入多条数据-网站建设-微信广告


使用 MySQLi 和 PDO 向 MySQL 插入多条数据


mysqli_multi_query() 函数可用来执行多条SQL语句。


以下实例向 "MyGuests" 表添加了三条新的记录:


实例 (MySQLi - 面向对象)


<?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();?>



实例 (MySQLi - 面向过程)


<?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);?>


实例 (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); // 开始事务 $conn->beginTransaction(); // SQL 语句 $conn->exec("INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"); $conn->exec("INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', 'mary@example.com')"); $conn->exec("INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Julie', 'Dooley', 'julie@example.com')"); // 提交事务 $conn->commit(); echo "新记录插入成功";}catch(PDOException $e){ // 如果执行失败回滚 $conn->rollback(); echo $sql . "<br>" . $e->getMessage();} $conn = null;?>


关键词:建设,广告,数据

74
73
25
news

版权所有© 亿企邦 1997-2025 保留一切法律许可权利。

为了最佳展示效果,本站不支持IE9及以下版本的浏览器,建议您使用谷歌Chrome浏览器。 点击下载Chrome浏览器
关闭