我正在使用PHP创建一个MYSQL数据库及其表格,其中插入了值。我希望使用相同的PHP文件创建数据库及其表。由于某种原因,未创建数据库及其表。如何一次创建数据库及其表?非常感谢,这是下面的代码:
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create database
$sql = "CREATE DATABASE school";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
$dbname = "school"; //database name
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = CREATE TABLE student (
'id' int(6) NOT NULL AUTO_INCREMENT,
'name' varchar(500) NOT NULL,
'gender' varchar(100) NOT NULL,
PRIMARY KEY ('id');
INSERT INTO 'student' ('id', 'name', 'gender') VALUES
(1, 'Cassidy Jackson', 'female'),
(2, 'jack Hilson', 'male');
if (mysqli_query($conn, $sql)) {
echo "Table school created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
答案 0 :(得分:0)
你有很多错误。您不打开连接但尝试创建数据库。在此之后,您关闭不存在的连接等。但您的SQL也有错误。首先,它们不是php的字符串,永远不会使用 列或表名的单引号,仅用于值。
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Create database
$sql = "CREATE DATABASE school";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully<br>";
} else {
echo "Error creating database: " . mysqli_error($conn) . "<br>";
}
mysqli_select_db ( $conn , "school" );
//database name
// Create connection
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "CREATE TABLE `school` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(500) NOT NULL,
`gender` VARCHAR(100) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `idschool_UNIQUE` (`id` ASC));";
if(mysqli_query($conn, $sql)){
echo "Table school created successfully<br>";
} else {
echo "Error creating table: " . mysqli_error($conn). "<br>";
}
$sql = "INSERT INTO `student` (id, name, gender) VALUES
(1, 'Cassidy Jackson', 'female'),
(2, 'jack Hilson', 'male')";
if (mysqli_query($conn, $sql)) {
echo "Values Inserted successfully<br>";
} else {
echo "Error ınsert values to table: " . mysqli_error($conn) . "<br>";
}
mysqli_close($conn);
?>