最新的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;
?>