php - Programmatic Equivalent Of Import in phpMyAdmin

433

I have a SqlDump.sql file that works just fine when I apply it using the Import feature of phpMyAdmin, however I need to be able to accomplish this programmatically. Being a noob, I tried to do something like this:

$SQL=file_get_contents('SqlDump.sql');
$DB=mysqli_connect('localhost','root','');
mysqli_select_db($DB,'somedb');
if (mysqli_multi_query($DB, $SQL)) {
    do {
        if ($result = mysqli_store_result($DB)) {
            mysqli_free_result($result);
        }
    } while (mysqli_next_result($DB));
}
$Err=mysqli_error($DB);
mysqli_close($DB);

But I get all kinds of mysql errors. Yet the same file works just fine when I import it using phpMyAdmin. How do I get this to work programmatically?

Error:

Can't create table 'somedb.t_sr_u_alertcode' (errno: 150)
982

Answer

Solution:

You have double-trouble.

That error is a foreign key constraint error. Some table you're trying to create probably has a foreign key to another table that hasn't yet been created.

I found some instances of the error here:

by googling this:

Second problem is that you'll probably get into trouble trying to import a large file because I don't think you can execute multiple sql commands seperated with an ; like you can in phpmyadmin. I'd suggest using a script like this one:

I haven't tried it myself, but I have no reason to believe it doesn't work.

727

Answer

Solution:

You could always just look at the source code

People are also looking for solutions to the problem: mysql - PHP - Drilling down Data and Looping with Loops

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.