最新的Web开发教程
 

PHP插入数据到MySQL


将数据插入到MySQL的使用库MySQLi和PDO

数据库和表创建之后,我们就可以开始将它们添加数据。

这里有一些语法规则可循:

  • 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_INCREMENT (like the "id" column)或TIMESTAMP (like the "reg_date" column) ,这是没有必要的SQL查询中指定; MySQL会自动添加值。

下面的例子中添加新的记录到"MyGuests"表:

实施例(MySQLi Object-oriented)

<?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', '[email protected]')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

实施例(MySQLi Procedural)

<?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', '[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;
?>