我的PHP代码一直遇到问题。我试图根据用户输入将数据插入6个字段,并且需要确保数据库/表在添加之前已经存在。我已经调用了一个查询(“如果不存在,则创建数据库'Students'”)和select_db('Students'),但它仍然返回错误,表明该数据库不存在。代码如下:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$link = mysqli_connect($servername, $username, $password);
$dbcheck = 'CREATE DATABASE `Students` IF NOT EXISTS';
$link->query($dbcheck);
$link->select_db("Students");
$students = "CREATE TABLE IF NOT EXISTS `Students` (
`id` int(11) unsigned NOT NULL auto_increment,
`fname` varchar(255) NOT NULL default '',
`lname` varchar(255) NOT NULL default '',
`address` varchar(255) NOT NULL default '',
`email` varchar(255) NOT NULL default '',
`phone` int(30) unsigned NOT NULL default '',
`dateofbirth` int(30) unsigned NOT NULL default '',
PRIMARY_KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8";
$link->query($students);
$FNAME = mysqli_real_escape_string($link, $_REQUEST['fname']);
$LNAME = mysqli_real_escape_string($link, $_REQUEST['lname']);
$ADDRESS = mysqli_real_escape_string($link, $_REQUEST['address']);
$EMAIL = mysqli_real_escape_string($link, $_REQUEST['email']);
$PHONE = mysqli_real_escape_string($link, $_REQUEST['phone']);
$DATEOFBIRTH = mysqli_real_escape_string($link, $_REQUEST['dateofbirth']);
if ($link->connect_error) {
die("Connection failed: " . $link->connect_error);
}
$query = "INSERT INTO Students (fname,lname,address,email,phone,dateofbirth)
VALUES ('$FNAME','$LNAME','$ADDRESS','$EMAIL','$PHONE','$DATEOFBIRTH')";
if ($link->query($query) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $query . "<br>" . $link->error;
}
$link->close();
?>
答案 0 :(得分:1)
语法为CREATE DATABASE IF NOT EXISTS Students