在創(chuàng)建完數(shù)據(jù)庫和表后,我們可以向表中添加數(shù)據(jù)。
以下為一些語法規(guī)則:
-
PHP 中 SQL 查詢語句必須使用引號
-
在 SQL 查詢語句中的字符串值必須加引號
-
數(shù)值的值不需要引號
-
NULL 值不需要引號
INSERT INTO 語句通常用于向 MySQL 表添加新的記錄:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
學(xué)習(xí)更多關(guān)于 SQL 知識,請查看我們的 SQL 教程。
在前面的幾個章節(jié)中我們已經(jīng)創(chuàng)建了表 "MyGuests",表字段有: "id", "firstname", "lastname", "email" 和 "reg_date"。 現(xiàn)在,讓我們開始向表填充數(shù)據(jù)。
|
注意: 如果列設(shè)置 AUTO_INCREMENT (如 "id" 列) 或 TIMESTAMP (如 "reg_date" 列),,我們就不需要在 SQL 查詢語句中指定值; MySQL 會自動為該列添加值。 |
以下實例向 "MyGuests" 表添加了新的記錄:
實例 (MySQLi - 面向?qū)ο?
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 創(chuàng)建連接
$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', '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";
// 創(chuàng)建連接
$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', '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;
?>
其實,你還可以在 PHP 的 MySQL 數(shù)據(jù)庫中插入多條數(shù)據(jù),這將在下面的一節(jié)內(nèi)容中提及。
更多建議: