在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
在创建完数据库和表后,我们可以向表中添加数据。 以下为一些语法规则:
INSERT INTO 语句通常用于向 MySQL 表添加新的记录: INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...) 学习更多关于 SQL 知识,请查看我们的 SQL 教程。 在前面的几个章节中我们已经创建了表 "MyGuests",表字段有: "id", "firstname", "lastname", "email" 和 "reg_date"。 现在,让我们开始向表填充数据。
以下实例向 "MyGuests" 表添加了新的记录: 实例 (MySQLi - 面向对象)<?php
$servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检测连接 if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', '[email protected]')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } 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("Connection failed: " . mysqli_connect_error()); } $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', '[email protected]')"; if (mysqli_query($conn, $sql)) { echo "New record created successfully"; } 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); $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', '[email protected]')"; // use exec() because no results are returned $conn->exec($sql); echo "New record created successfully"; } catch(PDOException $e) { echo $sql . "<br>" . $e->getMessage(); } $conn = null; ?> 其实,你还可以在 PHP 的 MySQL 数据库中插入多条数据,这将在下面的一节内容中提及。 |
请发表评论