我正在运行时创建数据库和表。当我执行代码时,它正在创建数据库,而不是表。它将引发错误:“未选择数据库”; 请引导我。
$sql = "CREATE DATABASE $db_name";
if ($this->db->query($sql) === TRUE) {
$errors = [];
$table1 = "CREATE TABLE `login_detail` (
`id` int(100) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`employee_id` varchar(100) NOT NULL,
`full_name` varchar(150) NOT NULL,
`password` varchar(100) NOT NULL,
`role` varchar(50) NOT NULL,
`profile_image` varchar(255) NOT NULL,
`status` varchar(100) NOT NULL DEFAULT '1')";
$table2 = "INSERT INTO `login_detail`
(`id`, `employee_id`, `full_name`,
`password`, `role`, `profile_image`, `status`)
VALUES (1, 'admin', 'admin',
'21232f297a57a5a743894a0e4a801fc3', 'admin',
'uploads/profiles/admin.jpg', '1')";
$tables = [$table1, $table2];
foreach($tables as $k => $sql1){
$query = $this->db->query($sql1);
if(!$query)
$errors[] = "Table $k : Creation failed ($this->db->error)";
else
$errors[] = "Table $k : Creation done";
}
foreach($errors as $msg) {
echo "$msg <br>";
}
} else {
echo "Error creating database: " . $this->db->error;
}
答案 0 :(得分:0)
您还应该告诉脚本使用数据库(请参见https://dev.mysql.com/doc/refman/5.7/en/use.html)
$sql = "CREATE DATABASE $db_name";
if ($this->db->query($sql) === TRUE) {
$sqlUse = "USE $db_name";
if ($this->db->query($sqlUse) === TRUE) {
...
}