使用PHP创建数据库的问题

时间:2018-03-03 06:03:09

标签: php validation syntax-error

我的PHP代码在EasyPHP中创建数据库时出现问题

<?php
$conn=mysqli_connect('localhost','root','');
if($conn)
    echo "<p>Connection set up successfully.</p>";
mysqli_query($conn, "DROP DATABASE IF EXISTS hotelDB");
if (mysqli_query($conn, "CREATE DATABASE hotelDB"))
    echo "<p>Database created successfully.</p>";
mysqli_select_db($conn, "hotelDB");
//room_type table
$myStatement= "CREATE TABLE room_type
(
room_type_id INT NOT NULL AUTO_INCREMENT,
room_type_name VARCHAR(100),
total_room INT DEFAULT 5,
CONSTRAINT pk_room_type PRIMARY KEY (room_type_id)
);";
//reservation table
$myStatement .="CREATE TABLE reservation
(
reservation_id INT NOT NULL AUTO_INCREMENT,
room_type_id INT NOT NULL
begin_date DATE NOT NULL
end_date DATE NOT NULL
confirm_number CHAR(13),
CONSTRAINT pk_reservation PRIMARY KEY (reservation_id),
CONSTRAINT fk_reservation_room_type FOREIGN KEY (room_type_id) REFERENCES
room_type (room_type_id)
);";
if (mysqli_multi_query($conn, $myStatement))
    echo "<p>Table created successfully.</p>";
mysqli_close($conn);
?>

我还是比较新的PHP。我通过PHP验证运行它,它说没有语法问题。我不知道从哪里开始。

2 个答案:

答案 0 :(得分:1)

您的SQL查询中有一些错误。您在第二个查询中遗漏了commas,我也在评论中对此进行了描述。始终使用此mysqli_error($conn)检测错误。

请尝试使用此代码

<?php
$conn=mysqli_connect('localhost','root','');
if($conn)
    echo "<p>Connection set up successfully.</p>";
mysqli_query($conn, "DROP DATABASE IF EXISTS hotelDB");
if (mysqli_query($conn, "CREATE DATABASE hotelDB"))
    echo "<p>Database created successfully.</p>";
mysqli_select_db($conn, "hotelDB");
//room_type table


$myStatement1= "CREATE TABLE room_type
    (
    room_type_id INT NOT NULL AUTO_INCREMENT,
    room_type_name VARCHAR(100),
    total_room INT DEFAULT 5,
    CONSTRAINT pk_room_type PRIMARY KEY (room_type_id)
    );";
//I have ran each query separately
if (mysqli_query($conn, $myStatement1))
    echo "<p>Table created successfully.</p>";

else

    echo mysqli_error($conn);//for detecting error in the last query if any
//reservation table
$myStatement2 ="CREATE TABLE reservation
    (
    reservation_id INT NOT NULL AUTO_INCREMENT,
    room_type_id INT NOT NULL, 
    begin_date DATE NOT NULL, 
    end_date DATE NOT NULL,  
    confirm_number CHAR(13),
    CONSTRAINT pk_reservation PRIMARY KEY (reservation_id),
    CONSTRAINT fk_reservation_room_type FOREIGN KEY (room_type_id) REFERENCES
    room_type (room_type_id)
    );";//You were missing commas in this query.
if (mysqli_query($conn, $myStatement2))
    echo "<p>Table created successfully.</p>";
else

    echo mysqli_error($conn);//for detecting error in the last query if any
mysqli_close($conn);
?>

完美无缺

答案 1 :(得分:0)

您正在使用&#34; root &#34;没有密码的用户连接到数据库。 您需要设置密码或更好以创建新的db用户。 默认情况下,允许使用root的远程连接,因此您需要GRAND远程访问。