greetings to all

There is a *.sql file (table, import from MySQL), there is a database on the site, in which there is a specific table (empty) into which you need to import the *.sql file. The solution is simple, go to the control panel of the site, and phppmyadmin, and import the table in 20 seconds.

Is it possible to do the same actions by means of php / mysql commands, and how?

    2 answers 2

    You can use the system command (system). I don’t know if this is possible in windows (I don’t know if there is a mysql command there), but in * nix you can do it like this:

     system('mysql -u <user> -p<password> dbname < filename.sql'); 
    • The answer is good, but I'm going to import data to the hosting. interested in writing PHP files that are thrown onto hosting and run - frank
    • @frank, well, so this is a piece of php file that will do what you need. Only now it is not known whether the system command on the hosting will be allowed ... - KryDos
    • Apparently on my hosting such a command is not supported. I registered the command itself in this way (myuser, mypass - user and password of database, mybase - database, filename.sql - file for import) system ('mysql -u myuser -p mypass mybase <filename.sql'); - frank

    If you need to parse * .sql in the body of php and execute queries sequentially, I use the following code:

      $dump=file_get_contents('path/to/file.sql'); $q=''; $state=0; $coco=0; for($i=0;$i<strlen($dump);$i++){ switch($dump{$i}){ case '"': if($state==0) $state=1; elseif($state==1) $state=0; break; case "'": if($state==0) $state=2; elseif($state==2) $state=0; break; case "`": if($state==0) $state=3; elseif($state==3) $state=0; break; case ";": if($state==0) { //echo $q."\n;\n"; mysql_query($q); $q=''; $state=4; $coco++; } break; case "\\": if(in_array($state,array(1,2,3))) $q.=$dump[$i++]; break; } if($state==4) $state=0; else $q.=$dump{$i}; } echo'Выполнено запросов: '.$coco; 

    Naturally, after connecting to the database and selecting the database (you obviously know how to do this). I do not remember where I was taken, but it works properly.

    • Dear, explain a little construction? in what place to register request INSERT? here in place of this: mysql_query ($ q); ? - frank
    • 2
      It is assumed that all the code, i.e. CREATE, INSERT, etc. there is already in the * .sql file (it is easy to read from a notebook) here is a group of switches that parse a handful of characters and pull out the SQL queries from them themselves, performing a read-trace. - timophey 1
    • cool of course, in my case 'Requests executed: 11', but I never saw any changes in the database - frank
    • one
      I use this code to build the basic database structure and its minimum content in the installer of the samopisny engine. Everything works fine. Debag you in hand. it is open, no one interferes with its waste products. - timophey 1
    • Thanks again for the code, it did not work. Himself too smart - frank