目录

PHP MySQL 插入数据


使用 MySQLi 和 PDO 将数据插入 MySQL

创建数据库和表后,我们可以开始向其中添加数据。

以下是一些需要遵循的语法规则:

  • SQL 查询必须在 PHP 中引用
  • SQL 查询中的字符串值必须用引号引起来
  • 数值不得加引号
  • 单词 NULL 不能被引用

INSERT INTO 语句用于向 MySQL 表添加新记录:

INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

要了解有关 SQL 的更多信息,请访问我们的SQL教程

在上一章中,我们创建了一个名为 "MyGuests" 的空表,其中包含五列:"id"、"firstname"、"lastname"、"email" 和 "reg_date"。现在,让我们用数据填充表格。

笔记:如果列是 AUTO_INCRMENT(如 "id" 列)或默认更新为 current_timesamp 的 TIMESTAMP(如 "reg_date" 列),则无需在 SQL 查询中指定; MySQL 会自动添加该值。

以下示例将新记录添加到 "MyGuests" 表:

示例(MySQLi 面向对象)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";

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";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";

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', 'john@example.com')";
  // 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;
?>