溫馨提示×

怎么用php創(chuàng)建數(shù)據(jù)庫和表

PHP
小億
86
2024-05-06 09:45:54
欄目: 編程語言

要使用PHP創(chuàng)建數(shù)據(jù)庫和表,你需要使用MySQL數(shù)據(jù)庫管理系統(tǒng)并通過PHP的MySQLi或PDO擴(kuò)展來與數(shù)據(jù)庫進(jìn)行交互。

以下是創(chuàng)建數(shù)據(jù)庫和表的步驟:

  1. 首先,連接到MySQL數(shù)據(jù)庫服務(wù)器:
$servername = "localhost";
$username = "username";
$password = "password";

$conn = new mysqli($servername, $username, $password);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
  1. 創(chuàng)建數(shù)據(jù)庫:
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
    echo "Database created successfully";
} else {
    echo "Error creating database: " . $conn->error;
}
  1. 選擇數(shù)據(jù)庫:
$conn->select_db("myDB");
  1. 創(chuàng)建表:
$sql = "CREATE TABLE users (
    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 created successfully";
} else {
    echo "Error creating table: " . $conn->error;
}
  1. 關(guān)閉數(shù)據(jù)庫連接:
$conn->close();

以上代碼示例演示了如何使用PHP連接到MySQL數(shù)據(jù)庫服務(wù)器、創(chuàng)建數(shù)據(jù)庫、選擇數(shù)據(jù)庫、創(chuàng)建表,并關(guān)閉數(shù)據(jù)庫連接。你可以根據(jù)自己的需求和表結(jié)構(gòu)修改相應(yīng)的SQL語句。

0