尝试从 CSV 中获取数据以使用 PHP 插入 mysql,读取但它不存储在数据库中

Try getting data from CSV to insert in mysql using PHP, Read but it is not storing in the database

所以我想从包含

的 CSV 文件中导入数据
name, lastname, age

我已成功导入数据并从每一列中获取数据,但由于某种原因未能成功存储信息:

我的代码如下:

<?php

class csv extends mysqli
{
    private $state_CSV = false; //Validate the status of the CSV file

    public function __construct()
    {
        parent::__construct("localhost","root","","database");
        if ($this->connect_error) {
            echo "Fail to connect to Database : ". $this->connect_error;
        }
    }

    //import file in to read all data one by one
    public function import ($file)
    {
      if (($file = fopen ($file,'r')) !==FALSE) //r = read
      {
        while (($row = fgetcsv($file,1000,",")) !== FALSE) {

                /* you will need process the row*/ 
                $fullname = $row[0] ;
                $lastname = $row[1];
                $age = $row[2];

                //separate firstname and middle name
                $name = explode(" ", $fullname);
                $firstname = $name[0]; // piece1
                $middlename = $name[1]; // piece2//explode firstname

                //make first letter capital
                $lastname = ucfirst(strtolower($lastname));

                //Insert value into the database
                $q = "INSERT INTO file (first,middle,last,age) VALUES (".$firstname.",".$middlename.",".$lastname.",".$age.")";

                    echo $q;        //open here to show what the query look like

                if ( $this->query($q)){
                    $this->state_CSV = true;    //if the query run perfectly

                }else{
                    $this->state_CSV = false; //if is not run perfectly
                }
            }
                //showing notification, problem 

                if ($this->state_CSV) {
                echo "Your data has been successfully imported";
                }else{
                echo "Something went wrong while importing your data";
            }
        }
    }
}
?>

它一直显示错误消息并且不记录 csv 文件中的任何数据

欢迎使用 Whosebug。由于 firstname、middlename 和 last name 可能是 SQL 中的 char 类型,因此在插入时它们需要单引号。使用您的语法,应该这样做:

$q = "INSERT INTO file (first,middle,last,age) VALUES ('".$firstname."','".$middlename."',"'.$lastname."',".$age.")";

此处一个好的调试方法是将您回显的 $q 值粘贴到 SQL 工具或命令行中并执行它。