PHP 創(chuàng)建 MySQL 表
一個數(shù)據(jù)表有一個唯一名稱,并有行和列組成。
使用 MySQLi 和 PDO 創(chuàng)建 MySQL 表
CREATE TABLE 語句用于創(chuàng)建 MySQL 表。
我們將創(chuàng)建一個名為 "MyGuests" 的表,有 5 個列: "id", "firstname", "lastname", "email" 和 "reg_date":
CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)
上表中的注意事項:
數(shù)據(jù)類型指定列可以存儲什么類型的數(shù)據(jù)。完整的數(shù)據(jù)類型請參考我們的 數(shù)據(jù)類型參考手冊。
在設(shè)置了數(shù)據(jù)類型后,你可以為沒個列指定其他選項的屬性:
- NOT NULL - 沒一行都必須含有值(不能為空),null 值是不允許的。
- DEFAULT value - 設(shè)置默認值
- UNSIGNED - 使用無符號數(shù)值類型,0 及正數(shù)
- AUTO INCREMENT - 設(shè)置 MySQL 字段的值在新增記錄時每次自動增長 1
- PRIMARY KEY - 設(shè)置數(shù)據(jù)表中每條記錄的唯一標識。 通常列的 PRIMARY KEY 設(shè)置為 ID 數(shù)值,與 AUTO_INCREMENT 一起使用。
每個表都應該有一個主鍵(本列為 "id" 列),主鍵必須包含唯一的值。
以下實例展示了如何在 PHP 中創(chuàng)建表:
實例 (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 to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
if ($conn->query($sql) === TRUE) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $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 to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . 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 to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
// use exec() because no results are returned
$conn->exec($sql);
echo "Table MyGuests created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
更多建議: