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);
}
?>
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);
}
?>
whith array_shift(file('filename.csv'))
will give you the first line of the document filename.csv
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With