In Php to dynamically get table name and fields from csv file and import to MYSQL

五迷三道 提交于 2020-01-26 03:48:29

问题


I have created a data-structure in Mysql with table name(CSV filename) and field names(CSV column names).

Right now I am importing the data from csv to Mysql table successfully Where as I am hard-coding csv file name and field name in script. How to dynamical fetch bec I have manny csv files to import into mysql.

<?php
include "db.php";
$filename = "C:\REQ\Status.csv";
if (($handle = fopen($filename, 'r')) !== FALSE)
     while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
     {
       print_r($data);
       $import="INSERT into status(status) values('$data[1]')";
       mysql_query($import) or die(mysql_error());

     }
 fclose($handle);

?>    

回答1:


I have implement this code and it is tested code. I think it is very use full

You have follow some rule:-

1.your csv file according to database table name (ex: db table name is users then csv should be users.csv)

2.Your csv file's first row should be db table fields name (ex: Id, name etc) after the start your data entry

3.you can download data source class from :- http://code.google.com/p/php-csv-parser/ because i have require below the code: require_once 'CSV/DataSource.php';

<?php
ini_set('memory_limit','512M');
$dbhost = "localhost";
$dbname = "excel_import";
$dbuser = "root";
$dbpass = "";

$conn=mysql_connect ($dbhost, $dbuser, $dbpass) or die ("I cannot connect to the database because: " . mysql_error());
mysql_select_db($dbname) or die("Unable to select database because: " . mysql_error());


require_once 'CSV/DataSource.php';


$filename = "users.csv";
$ext = explode(".",$filename);
$path = "uploads/".$filename;

$dbtable = $ext[0];

import_csv($dbtable, $path);


function import_csv($dbtable, $csv_file_name_with_path)
{
    $csv = new File_CSV_DataSource;
    $csv->load($csv_file_name_with_path);

    $csvData = $csv->connect();

    $res='';
    foreach($csvData  as $key)
    {
        $myKey ='';
        $myVal='';
        foreach($key as $k=>$v)
        {
            $myKey .=$k.',';
            $myVal .="'".$v."',";
          }

        $myKey = substr($myKey, 0, -1);
        $myVal = substr($myVal, 0, -1); 
        $query="insert into ".$dbtable." ($myKey)values($myVal)";
        $res=  mysql_query($query);

    }

    if($res ==1)
    {

                echo "record successfully Import.";

    }else{

                echo "record not successfully Import.";
    }
}



回答2:


Something like this:

function integrate($filename)
{
if (($handle = fopen($filename, 'r')) !== FALSE)
     while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
     {
       print_r($data);
       $import="INSERT into status(status) values('$data[1]')";
       mysql_query($import) or die(mysql_error());

     }
 fclose($handle);
}


$files = scandir('folder/');
foreach($files as $file) {
  //pre-checking (if already integrated, if CSV etc..)
  integrate($file);
}



回答3:


If you run it as a PHP script, you could get the filename as an argument with $argv[1] You would need to do some checking that the file exists, though.




回答4:


If the file name and table name match, then wherever you're entering or retrieving the file name from, you can use that same value in the query:

$filename = "Status";

$table_name = strtolower( $filename );

$filename = "C:\REQ\{$filename}.csv";

if (($handle = fopen($filename, 'r')) !== FALSE)
     while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
     {
       print_r($data);
       $import="INSERT into {$table_name}(status) values('$data[1]')";

For the column names, I'd recommend putting them in the first row of your CSV files and parsing them from there, e.g.:

if (($handle = fopen($filename, 'r')) !== FALSE)

    $columns = fgets($handle, 1000);

     while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
     {
       print_r($data);
       $import="INSERT into {$table_name}({$columns}) values('{$data[1]}')";

I'd also recommend considering building up a single SQL query string for a multiple-row INSERT. E.g.

$values = array();

     while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
     {
       print_r($data);
       $values[] = "('{$data[1]}')";
       ...
     }

     $values = join( ",\n\n", $values );

     $insert = "INSERT into {$table_name}({$columns}) values {$values}";


来源:https://stackoverflow.com/questions/11810599/in-php-to-dynamically-get-table-name-and-fields-from-csv-file-and-import-to-mysq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!