Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read first row from csv file and create table according to it(csv file fields)

Tags:

php

mysql

csv

Read first row from csv file and create table automatically according to it(csv file fields) in mysql. Looking for PHP script? I have tried this

 <?php

$arr = array(array(),array());
$num = 0;
$row = 0;
$handle = fopen("./contacts.csv", "r");


while($data = fgetcsv($handle,1000,",")){   
    $num = count($data);
    for ($c=0; $c < $num; $c++) {
            $arr[$row][$c] = $data[$c];
    }
    $row++;
}


$con = mysql_connect('localhost','root','');
mysql_select_db("excel_database",$con);

for($i=1; $i<$row; $i++){
$sql = "INSERT INTO contacts VALUES ('".$arr[$i][0]."','".$arr[$i][1]."','".$arr[$i][2]."','".$arr[$i][3]."','".$arr[$i][4]."','".$arr[$i][5]."')";
mysql_query($sql,$con);
}

?>
like image 802
AWA Avatar asked Dec 07 '22 04:12

AWA


2 Answers

This is half way to your question.

<?php
    $row = 1;
    if (($handle = fopen("ab.csv", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $num = count($data);
            echo "<p> $num fields in line $row: <br /></p>\n";
            $row++;
            for ($c=0; $c < $num; $c++) {
                echo $data[$c] . "<br />\n";

            }
        }

        fclose($handle);
    }
    ?>
like image 50
bzbz Avatar answered Jan 14 '23 05:01

bzbz


whith array_shift(file('filename.csv')) will give you the first line of the document filename.csv

like image 29
Friedrich Avatar answered Jan 14 '23 05:01

Friedrich