數據庫由一個或多個表的。
您將需要特殊的CREATE權限才能創建或刪除MySQL數據庫。
創建使用庫MySQLi和PDO MySQL數據庫
CREATE DATABASE語句用於在MySQL中創建一個數據庫。
下面的示例創建一個名為數據庫"myDB"
實施例(MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password =
"password";
// Create connection
$conn =
new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo
"Error creating database: " . $conn->error;
}
$conn->close();
?>
注意:當您創建一個新的數據庫,你只能指定前三個參數和mysqli對象(服務器名,用戶名和密碼)。
提示:如果你必須使用一個特定的端口,添加一個空字符串數據庫名參數,如:新mysqli("localhost", "username" , "password" , "" , port)
實施例(MySQLi Procedural)
<?php
$servername = "localhost";
$username = "username";
$password =
"password";
// Create connection
$conn = mysqli_connect($servername,
$username, $password);
// Check connection
if (!$conn) {
die("Connection
failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE
DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database
created successfully";
} else {
echo "Error
creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
注意:以下PDO例如創建一個名為數據庫"myDBPDO"
實施例(PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB",
$username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
// use exec() because no
results are returned
$conn->exec($sql);
echo "Database created successfully<br>";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
提示:PDO的一大好處是,它具有異常類來處理我們的數據庫查詢可能出現的任何問題。 如果異常是在try {}塊中拋出,腳本停止執行並直接流到第一catch() {}塊。 在catch塊上面我們呼應的SQL語句和生成的錯誤消息。