我如何使用CodeIgniter执行sql脚本并将数据传递给它?

时间:2014-08-05 19:48:34

标签: php mysql sql codeigniter

我有一个sql脚本来生成一个数据库,我希望当我按下按钮注册它时调用sql脚本但是在传递给sql脚本数据之前将调用数据库。

有些像这样:

make_db($ name_db);

4 个答案:

答案 0 :(得分:4)

$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

答案 1 :(得分:1)

根据文件的大小,最好将其转换为Codeigniter模型函数,但如果不可能,您可以尝试类似exec("mysql < sql_file_name.sql");

的内容

看起来你想要将DB的名称传递给函数,所以你可以从文件中取出'CREATE DATABASE whatever'行,将它作为普通的codeigniter查询运行,然后'exec'其余的该数据库的脚本。

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

您可以这样做

    $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