<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "onlinestores";
// Run the actual connection here
$connect_dude=mysqli_connect("$db_host","$db_username","$db_pass","$db_name");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
//creating table
<?php
include "connect_to_db.php";
$sql_command="CREATE TABLE admin(
id NOT NULL auto_increment,
username varchar(16) NOT NULL,
password varchar(16) NOT NULL,
last_login date NOT NULL,
PRIMARY KEY(id),
UNIQUE KEY username(username)
)";
if(mysqli_query($connect_dude,"$sql_command")){
echo "ookie dookie";
}else {
echo "it didn't work";
}
?>
代码不会在数据库中创建任何表,并向我显示echo语句“它不起作用”。
答案 0 :(得分:2)
您的SQL有语法错误。
id
列未命中int
UNIQUE KEY username(username)
应为UNIQUE KEY(username)
试试这个:
$sql_command = "CREATE TABLE admin
(id int NOT NULL auto_increment,
username varchar(16) NOT NULL,
password varchar(16) NOT NULL,
last_login date NOT NULL,
PRIMARY KEY(id),
UNIQUE KEY(username))";
要捕获mysql调用中的错误,请使用mysqli_error()
else {
echo "it didn't work because: " . mysqli_error($connect_dude);
}
答案 1 :(得分:1)
尝试这样做,确保在生产代码之前有适当的变量名称,
connect_to_db.php文件:
<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "onlinestores";
// Run the actual connection here
$mysqli=mysqli_connect($db_host, $db_username, $db_pass, $db_name);
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
?>
create_table.php文件:
<?php
include "connect_to_db.php";
$sql_command="CREATE TABLE admin(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(16) NOT NULL UNIQUE KEY,
pass VARCHAR(16) NOT NULL,
last_login DATE NOT NULL
)";
if($mysqli->query($sql_command) === TRUE)
echo "ookie dookie";
else
echo "it didn't work";
?>
答案 2 :(得分:0)
替换您的代码:
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "onlinestores";
// Run the actual connection here
$connect_dude=mysqli_connect("$db_host","$db_username","$db_pass","$db_name");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
//creating table
<?php
include "connect_to_db.php";
$sql_command="CREATE TABLE admin(
id int NOT NULL auto_increment,
username varchar(16) NOT NULL,
password varchar(16) NOT NULL,
last_login date NOT NULL,
PRIMARY KEY(id),
UNIQUE KEY username(username)
)";
if(mysqli_query($connect_dude,"$sql_command")){
echo "ookie dookie";
}else {
echo "it didn't work";
}
?>