简体   繁体   中英

PHP/MYSQL: Importing csv files through php into a mysql table

I have been trying this code I found from this site here: https://www.johnboyproductions.com/blog/tutorial-import-a-csv-file-using-php-and-mysql

It works perfectly for me locally, but when I try the code on a live site. It says that the data is imported but does not reflect in the database. I am adding the code below:

if ($_FILES[csv][size] > 0) { 

//get the csv file 
$file = $_FILES[csv][tmp_name]; 
$handle = fopen($file,"r"); 

//loop through the csv file and insert into database 
do { 
    if ($data[0]) { 
        mysqli_query("INSERT INTO tablename VALUES 
            ( 
                '".addslashes($data[0])."', 
                '".addslashes($data[1])."'
            ) 
        "); 
    } 
} while ($data = fgetcsv($handle,1000,",","'")); 
// 

//redirect 
header('Location: filename.php?success=1'); die; 

} 

That's the functionality part, I will post the form section below:

            <form action="" method="post" enctype="multipart/form-data" name="form1" id="form1"> 
            Choose your file: <br /> 
            <input name="csv" type="file" id="csv" /> 
            <input type="submit" name="Submit" value="Submit" /> 
            </form> 

Any help will be greatly appreciated. Thanks

I have tried another code that was used initially which is working now:

if(isset($_POST['Submit']))
{

if ($_FILES['csv']['size'] > 0)
{ 

//get the csv file 
$file = $_FILES['csv']['tmp_name']; 
$handle = fopen($file,"r"); 


$firstRow = true;

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{

if($firstRow) { $firstRow = false; }
else {

 $str="INSERT INTO tablename VALUES 
            ('' ,
                '".addslashes($data[0])."', 
                '".addslashes($data[1])."'
            ) ";




            $result = mysqli_query($connection,$str);
            if($result)
                $cnt++;
}
}

fclose($handle);

//redirect 
// header('Location: filename.php?success=1'); die; 

} 


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM