我怎么能使用CodeIgniter执行一个SQL脚本,并传递数据呢?(How i can execu

2019-10-20 15:33发布

我有一个SQL脚本生成一个数据库,我想,当我按下按钮进行注册调用SQL脚本,但通至该数据库将如何被称为SQL脚本数据之前。

一些这样的:

make_db($ name_db);

Answer 1:

根据文件的大小,它可能是最好把它转换成一个笨的借鉴作用,但如果这不是一个可能性,你可以尝试像exec("mysql < sql_file_name.sql");

它看起来像你想的DB的名称传递到函数,所以你可以拿出你的文件的“CREATE DATABASE什么”行,运行它作为一个正常的笨查询,然后“EXEC”的脚本的其余部分该数据库。

以这种方式显然创建数据库一般是不是一个好主意,但我在这里不是来判断:-)



Answer 2:

$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



Answer 3:

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

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


Answer 4:

你可以像下面这样做

    $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



文章来源: How i can execute a sql script with CodeIgniter and pass data to it?