How i can execute a sql script with CodeIgniter an

2019-07-29 16:28发布

问题:

I have a sql script to generate a database and I want that when I press the button register it call to the sql script but before pass to the sql script data about how the database will be called.

some like this:

make_db($name_db);

回答1:

Depending on the size of the file, it might be best to convert it into a Codeigniter model function, but if that's not a possibility, you could try something like exec("mysql < sql_file_name.sql");

It looks like you want to pass the name of the DB into the function, so you could take the 'CREATE DATABASE whatever' line out of your file, run it as a normal codeigniter query, and then 'exec' the rest of the script for that database.

Obviously creating databases in this way is generally not a great idea, but I'm not here to judge :-)



回答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);   
}

original post is here : https://gist.github.com/Relequestual/4088557



回答3:

That is a different approach, try

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


回答4:

You can do it like this

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

I got this process from here https://stackoverflow.com/a/19752106/3602846