我想使用php在我的数据库中插入一个csv文件。我尝试了以下代码,但它给出了以下错误
致命错误:在第25行的C:\ xampp \ htdocs \ ICT_project \ class.import.php中调用null上的成员函数exec()
<?php
include 'connection.php';
class Import {
private $pdo;
public function __construct() {
$obj_connect = new DBconnect();
$this->pdo = $obj_connect->db_con;
}
public function import_csv() {
$extension= end(explode(".", basename($_FILES['file']['name'])));
if (isset($_FILES['file']) && $_FILES['file']['size'] < 10485760 && $extension=='csv') {
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
try {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
//$num = count($data);
$importSQL = "INSERT INTO tbl_applicants(application_no, applicant_name,applicant_email, applicant_mobile, applicant_address) VALUES('$data[0]','$data[1]')";
$this->pdo->exec($importSQL);
}
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
}
我的tbl_applicants
有五个字段:application_no
,applicant_name
,applicant_email
,applicant_mobile
,applicant_address
。
在csv文件中,我有两行数据,上面有五个字段。我不明白插入查询会是什么?
嗨,这是更新的代码,工作正常。 现在我想跳过我的.csv文件的第一行,它通常包含标题(ID,名称,电子邮件,地址)。我怎么能这样做?
<?php
include 'connection.php';
class Import {
private $pdo;
public function __construct() {
$obj_connection = new Db_connection();
$this->pdo = $obj_connection->connection();
}
public function import_csv() {
$extension= end(explode(".", basename($_FILES['file']['name'])));
if (isset($_FILES['file']) && $_FILES['file']['size'] < 10485760 && $extension=='csv') {
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
try {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$importSQL = "INSERT INTO tbl_applicants ( application_no, applicant_name, applicant_email, applicant_mobile, applicant_address ) VALUES('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]')";
$this->pdo->query($importSQL);
}
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
}
}
答案 0 :(得分:0)
请将此插入查询替换为上述查询。
$importSQL = "INSERT INTO tbl_applicants
(application_no, applicant_name,applicant_email, applicant_mobile, applicant_address)
VALUES('$data[0]','$data[1]','','','')";
答案 1 :(得分:0)
没有看到数据只是猜测你上面使用的是什么,但也许你只需要从csv中添加剩余的字段?
$importSQL = "INSERT INTO `tbl_applicants`
( application_no, applicant_name, applicant_email, applicant_mobile, applicant_address )
VALUES
('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]')"