我已编写此代码,但仍无法在数据库中创建表。只输出是:
“数据库已创建....对不起表未创建”。
<?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"; }
?>
答案 0 :(得分: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代码,从而无法获得任何结果。
答案 1 :(得分:0)
CREATE TABLE
语句需要指定要使用的数据库,或者需要使用mysqli_select_db()
设置默认数据库。
$creatingdatabase = "CREATE DATABASE IF NOT EXISTS quest";
$query1 = mysqli_query($con, $creatingdatabase);
mysqli_select_db($con, "quest");