PHP MySQL 建立資料庫
在本教程中,你將學習如何使用 PHP 在 MySQL 中建立資料庫。
使用 PHP 建立 MySQL 資料庫
現在你已經瞭解瞭如何開啟與 MySQL 資料庫伺服器的連線。在本教程中,你將學習如何執行 SQL 查詢來建立資料庫。
在儲存或訪問資料之前,我們需要先建立一個資料庫。該語句用於在 MySQL 中建立新資料庫。 CREATE DATABASE
讓我們使用該 CREATE DATABASE
語句進行 SQL 查詢,之後我們將通過將其傳遞給 PHP mysqli_query()
函式來執行此 SQL 查詢,以最終建立我們的資料庫。以下示例建立名為 demo 的資料庫。
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt create database query execution
$sql = "CREATE DATABASE demo";
if(mysqli_query($link, $sql)){
echo "Database created successfully";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$mysqli = new mysqli("localhost", "root", "");
// Check connection
if($mysqli === false){
die("ERROR: Could not connect. " . $mysqli->connect_error);
}
// Attempt create database query execution
$sql = "CREATE DATABASE demo";
if($mysqli->query($sql) === true){
echo "Database created successfully";
} else{
echo "ERROR: Could not able to execute $sql. " . $mysqli->error;
}
// Close connection
$mysqli->close();
?>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
try{
$pdo = new PDO("mysql:host=localhost;", "root", "");
// Set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage());
}
// Attempt create database query execution
try{
$sql = "CREATE DATABASE demo";
$pdo->exec($sql);
echo "Database created successfully";
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
// Close connection
unset($pdo);
?>
提示: 設定 PDO::ATTR_ERRMODE
屬性以 PDO::ERRMODE_EXCEPTION
告知 PDO 在發生資料庫錯誤時丟擲異常。