Search code examples
phpmysqlfgetcsv

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


So I want to import data from CSV file which consist of

name, lastname, age

I have successfully import the data and also getting the data from each column but it for some reason didn't manage to store the info:

My code as as below:

<?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";
            }
        }
    }
}
?>

It keep showing the error message and not recording any data from the csv files


Solution

  • Welcome to stackoverflow. Since firstname, middlename and last name are likely char types in SQL, they need single quotes in the insert. Using your syntax, something like this should do it:

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

    A good debugging method here would be to paste the $q value that you echo into a SQL tool or command line and execute it.