2016-02-01 52 views
-1

我是PHP新手,需要一些解釋。這裏是我們用PHP連接MySQL的代碼。你能否向我解釋一下連接的聲明在哪裏?我只能看到我們定義了$ conn的價值,但它是否也意味着執行?另一件事是:我們在哪裏創建數據庫?我可以看到我們將字符串「CREATE DATABASE myDB」作爲一個值賦給$ sql,並且我們有一個if語句,但是表達式($ conn-> query($ sql)=== TRUE)是否也被評估?對我來說很奇怪,有人可以向我解釋嗎?! :) 謝謝!當使用以下代碼在PHP中使用PHP創建數據庫時,我們在哪裏建立連接,以及在哪裏創建數據庫?

<?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(); 
?> 

回答

1

下面是對哪些線做什麼的簡單解釋。如果您想具體瞭解這些內容的各個部分,請說出哪些內容可以進一步向您解釋。或者正確的鏈接指向。

我注意到您正在使用W3Schools示例,因爲它幾乎完全複製並粘貼。你在你的機器上安裝了MySQL並創建了一個用戶名和密碼?

<?php 
    $servername = "localhost"; // This is the location of your server running MySQL 
    $username = "username"; // This is the username for MySQL 
    $password = "password"; // This is the password for MySQL 

    // Create connection 
    $conn = new mysqli($servername, $username, $password); // This is where you create a connection 

    // Check connection 
    if ($conn->connect_error) { // This checks if the connection happened 
     die("Connection failed: " . $conn->connect_error); // and produces an error message if not 
    } // otherwise we move on 

    // Create database 
    $sql = "CREATE DATABASE myDB"; // This is the SQL query which is sent to the MySQL server 
    if ($conn->query($sql) === TRUE) { // When the if statement begins here, it executes the query and test if it returns true 
     echo "Database created successfully"; // If it returns true then here is the message is returns 
    } 
    else { 
     echo "Error creating database: " . $conn->error; // Or if there was error with the query this is returned 
    } 

    $conn->close(); // Close the connection when it is no longer in use 
?> 
+0

謝謝你的答案!我只是想設立一切。我已經有webmatrix了。我是否也需要安裝MySQL? – Lumpy79

+0

不用擔心,是的,你需要安裝MySQL服務器。你可以在MySQL網站和w3schools上獲得這方面的指導,以幫助你入門 –

0

雖然,你的問題在這裏不屬於(這個地方,以幫助你的編碼問題),但我會給你說明一下。

PHP讀取每一行並執行它。創建連接部分使用「新」對象打開一個新連接並將其保存爲變量($ conn),

($conn->connect_error)檢查連接是否成功使用connect_error屬性。如果它已連接,請繼續,否則通過並錯誤並停止。

如果連接成功,則根據在變量($ conn)中打開的連接創建數據庫。

相關問題