简体   繁体   中英

Import data from CSV and Insert it into Mysql

I'm trying to import data from a CSV file to and Insert it into Mysql Database table using PHP Script. So far I have managed to get the message alert('Import done') , but I'm always getting this error:

在此处输入图片说明

Does anyone know why I'm always getting this Error? I have tried to insert the data in different ways but they always seem to get the same error:

$item1 = mysqli_real_escape_string($conn, $data[1]);
$item1 = mysqli_real_escape_string($conn, $_POST($data[1]));
$item1 = $_POST($data[1]); 

This is my code:

<?php
include('Conexion.php');
if(isset($_POST["submit"]))
{
    if($_FILES['file']['name'])
    {
        $filename = explode(".", $_FILES['file']['name']);
        if($filename[1] == 'csv')
        {
            $handle = fopen($_FILES['file']['tmp_name'], "r");
            while($data = fgetcsv($handle))
            {
                /*$item1 = mysqli_real_escape_string($conn, $data[1]);
                $item1 = mysqli_real_escape_string($conn, $_POST($data[1]));*/
                $item1 = $_POST($data[1]); /*This is line 15*/

                $query = "INSERT INTO excel(title) values('$item1')";
                mysqli_query($conn, $query);
            }
            fclose($handle);
            echo "<script>alert('Import done');</script>";
        }
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body>
<form method="post" enctype="multipart/form-data">
    <div align="center">
        <label>Select the CSV:</label>
        <input type="file" name="file" />
        <input type="submit" name="submit" value="Import" class="btn btn-info" />
    </div>
</form>
</body>
</html>

This is my table:

CREATE TABLE excel (
  excercise_id int(11) NOT NULL AUTO_INCREMENT,
  title text,
  PRIMARY KEY (excercise_id)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

How many columns do you have in your file ?

But, I think that you can try this:

 while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
     if (isset($data[1])) {         
         $item1 = $data[1];
         $query = "INSERT INTO excel(title) values('$item1')";
         mysqli_query($conn, $query); 
    } 
}

You can check the first example in this documentation : https://www.php.net/manual/fr/function.fgetcsv.php

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