使用CodeIgniter从.sql文件执行SQL

epfja78i  于 7个月前  发布在  其他
关注(0)|答案(4)|浏览(60)

我有一个SQL脚本来生成一个数据库,我想当我按下按钮注册它调用SQL脚本,但在传递到SQL脚本数据如何将被称为数据库。
比如说:
第一个月

flvlnr44

flvlnr441#

$sql = file_get_contents("update-001.sql");

/*
Assuming you have an SQL file (or string) you want to run as part of the migration, which has a number of statements...
CI migration only allows you to run one statement at a time. If the SQL is generated, it's annoying to split it up and create separate statements.
This small script splits the statements allowing you to run them all in one go.
*/

$sqls = explode(';', $sql);
array_pop($sqls);

foreach($sqls as $statement){
    $statment = $statement . ";";
    $this->db->query($statement);   
}

字符串
原文链接:https://gist.github.com/Relequestual/4088557

hc2pp10m

hc2pp10m2#

根据文件的大小,最好将其转换为Codeigniter模型函数,但如果不可能,可以尝试类似exec("mysql < sql_file_name.sql");的方法
看起来你想把数据库的名称传递给函数,所以你可以从文件中取出“CREATE DATABASE whatever”行,作为普通的codeigniter查询运行它,然后“exec”该数据库的其余脚本。
显然,以这种方式创建数据库通常不是一个好主意,但我不是在这里评判:-)

kr98yfug

kr98yfug3#

这是一种不同的方法,尝试

$this->db->query(file_get_contents("MySqlScript.sql"));

字符串

mo49yndu

mo49yndu4#

你可以这样做

$CI = & get_instance();
    $templine = '';
    // Read in entire file
    $lines = file('update-001.sql');
    foreach($lines as $line) {
        // Skip it if it's a comment
        if (substr($line, 0, 2) == '--' || $line == '')
            continue;

        // Add this line to the current templine we are creating
        $templine.=$line;

        // If it has a semicolon at the end, it's the end of the query so can process this templine
        if (substr(trim($line), -1, 1) == ';') {
            // Perform the query
            $CI->db->query($templine);
            // Reset temp variable to empty
            $templine = '';
        }
    }

字符串
我从这里得到这个过程https://stackoverflow.com/a/19752106/3602846

相关问题