gzahid

gzahid

Joined
Nov 04, 2015

Activity Stream

gzahid commented on a Page, CSV to mySQL - Create Table and Insert Data  -  Nov 04, 2015

Hi,

I keep getting error on "Please provide a file name\n"; exit; "

Does the file name that user upload has to be "filename.csv" Also I am getting Null for $argv

I am first uploading the file to server which is loading fine, and then running this.

if(empty($errors)==true){ // start upload

            $host = 'localhost';
            $user = 'root';
            $pass = 'root';
            $database = 'db_name';

            $db = mysql_connect($host, $user, $pass);
            mysql_query("use $database", $db);

            /********************************************************************************/
            // Parameters: filename.csv table_name

            $argv = $_SERVER[argv];

            if($argv[1]) { $file = $argv[1]; }
            else {
                echo "Please provide a file name\n"; exit; 
            }
            if($argv[2]) { $table = $argv[2]; }
            else {
                $table = pathinfo($file);
                $table = $table['filename'];
            }

            /********************************************************************************/
            // Get the first row to create the column headings

            $fp = fopen($file, 'r');
            $frow = fgetcsv($fp);

            foreach($frow as $column) {
                if($columns) $columns .= ', ';
                $columns .= "`$column` varchar(250)";
            }

            $create = "create table if not exists $table ($columns);";
            mysql_query($create, $db);

            /********************************************************************************/
            // Import the data into the newly created table.

            $file = $_SERVER['PWD'].'/'.$file;
            $q = "load data infile '$file' into table $table fields terminated by ',' ignore 1 lines";
            mysql_query($q, $db);

        } // end upload

Thanks for all your help in advance.

Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.