2016-07-20 112 views
0

我寫過這段代碼,但仍然無法在數據庫中創建表。並且輸出結果爲:表無法創建

「數據庫已創建...對不起表格」。

<?php         
    include 'connection.php'; 
    //Creating database 
    $creatingdatabase = "CREATE DATABASE IF NOT EXISTS quest"; 
    $query1 = mysqli_query($con, $creatingdatabase); 
    if($query1){ 

     echo "database created...."; 
     //creating tables 
     $creatingtable = "CREATE TABLE quiz (
         id INT(6) AUTO_INCREMENT PRIMARY KEY, 
         questions VARCHAR(255) NOT NULL, 
         optiona VARCHAR(255) NOT NULL, 
         optionb VARCHAR(255) NOT NULL, 
         optionc VARCHAR(255) NOT NULL, 
         optiond VARCHAR(255) NOT NULL, 
         answer VARCHAR(50) NOT NULL 
               )"; 
     $query2 = mysqli_query($con, $creatingtable); 
     if($query2){echo "table created...";} 
     else { echo "sorry... table not created"; } 

    } 
    else { echo "database can not be created"; } 
?> 

This is the output as seen in the browser.

+1

更改'else {echo「sorry ... table not created」; }'to'else {echo「sorry ... table not created:」。mysqli_error($ con); }'這樣我們可以看到錯誤:) – DiceXQ

回答

0

CREATE TABLE語句需要指定要使用的數據庫,或者需要使用mysqli_select_db()來設置默認數據庫。

$creatingdatabase = "CREATE DATABASE IF NOT EXISTS quest"; 
$query1 = mysqli_query($con, $creatingdatabase); 
mysqli_select_db($con, "quest"); 
0
<?php 
$servername = 'localhost'; 
$username = 'root'; 
$password = 'xxxxx'; 

$conn = new mysqli($servername, $username, $password); 
if ($conn->connect_error) { 
    die("Connection failed: " . $conn->connect_error); 
} 
// Create database 
$sql = "CREATE DATABASE guest"; //Set name database here 
if ($conn->query($sql) === TRUE) { 
    $conn = mysqli_connect($servername, $username, $password,'guest');//Set name database here 
    if ($conn->connect_error) { 
     die("Connection failed: " . $conn->connect_error); 
    } 
    $query = "CREATE TABLE quiz (
     id INT(6) AUTO_INCREMENT PRIMARY KEY, 
     questions VARCHAR(255) NOT NULL, 
     optiona VARCHAR(255) NOT NULL, 
     optionb VARCHAR(255) NOT NULL, 
     optionc VARCHAR(255) NOT NULL, 
     optiond VARCHAR(255) NOT NULL, 
     answer VARCHAR(50) NOT NULL 
    )"; 
    if ($conn->query($query) === TRUE) { 
     echo "Table users created successfully"; 
    } else { 
     echo "Error creating table: " . $conn->error; 
    } 
} else { 
    echo "Error creating database: " . $conn->error; 
} 

$conn->close(); 
?> 

但我不建議用戶可以在你的SQL Server創建新的數據庫。

就安全性而言,最好是已經創建了一個數據庫,然後只需添加用戶數據即使它是第一條記錄。用戶無法將數據輸入到Web表單中,然後間接運行SQL代碼,從而無法獲得任何信息。