2

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
  • This question would be much clearer and more useful if the minimal reproducible example contained sample SQL text. Commented Nov 2, 2023 at 4:33

4 Answers 4

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

The problem of this approach is the fact of some fields values may contained the ';' char.
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 :-)

Comments

0

That is a different approach, try

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.