简体   繁体   English

如何在使用Codeigniter创建表时选择数据库?

[英]How to select database at the run-time of creating tables using Codeigniter?

I am creating database and tables at the run-time. 我在运行时创建数据库和表。 When I execute code it is creating database but not tables. 当我执行代码时,它正在创建数据库,而不是表。 It throws an error :"No database selected"; 它将引发错误:“未选择数据库”; Please guide me. 请指导我。

$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;
}

You should additionaly tell your script to use the database (see https://dev.mysql.com/doc/refman/5.7/en/use.html ) 您还应该告诉脚本使用数据库(请参阅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) {
    ...
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM