How to import CSV files to MySQL from PHP and SSH

How to import CSV files to MySQL from PHP and SSH

cdmon ensures the security and proper operation of its services. For this reason, certain insecure MySQL functionalities for loading local files in bulk are not available. Below we explain three methods to import data into MySQL.
 
1.-Import a CSV file into MySQL from PHP

To perform a basic data import from a CSV file (Comma Separated Value) from PHP to MySQL, the native PHP function "fgetcsv" is used (http://php.net/manual/en/function.fgetcsv.php).
 
Below is an example PHP script that performs this type of import:
 
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {    $import = "INSERT INTO $table (text, number) VALUES ('$data[0]', '$data[1]')";    mysql_query($import) or die(mysql_error());  }fclose($handle);}
 
More information about the "fgetcsv" function: http://php.net/manual/en/function.fgetcsv.php
 
We also recommend using specialized third-party libraries for data import in PHP, for example the “data-import” library by David de Boer available here: https://github.com/ddeboer/data-import#csvreader
 
You should take the following aspects into account when importing data from PHP:
  • The execution time limit of a PHP script.
  • The memory limit that a PHP script can consume.
If any of the limits established in your hosting plan are exceeded, the process will not complete correctly.
 
2.-Import an SQL file into MySQL from SSH

With SSH access enabled (How to enable SSH access) on your hosting, you can perform a console import with the following command:
 
$ cat "archivo_importar.sql" | mysql -u Usuario -p NombreBaseDeDatos
 
  1. User: MySQL user.
  2. DatabaseName: name of the destination database where the queries defined in “archivo_importar.sql” will be executed.
 
3.-Import an SQL file into MySQL from the Control Panel
 
To perform an SQL data import into MySQL from the Control Panel, follow the steps described in How to import MySQL databases from the Control Panel.
 
 
For any questions, you can contact us.