1

I'm trying to populate a mysql database with the contents of a .csv file using php. I'd like to do it using php code (no phpadmin). I consulted another thread on stackoverflow (populating database from csv file using php) but am still getting stuck. Here is my code:

$file = fopen("input.csv", "r");

while ($data = fgetcsv($file, $lineLength = 0, $delimiter = ",")) {
    $added = "INSERT INTO Items VALUES(".$data.")";
    if($connection->query($added) === TRUE)  {
        echo "Values successfully added!";
    }  else {
        echo "Error inserting values: " . $connection->error;
    }

Some context: earlier in the code, I create a database, connect to it, and create a table in the database. That part works fine. I just get an error when I try to populate the database from a .csv file. Here is the error message I get:

Notice: Array to string conversion in C:\xampp\htdocs\assignment8\init.php on line 64
Error inserting values: Unknown column 'Array' in 'field list'

I get this message 12 times, which corresponds with the number of rows in the .csv file I'm trying to import. "Line 64" corresponds with the line in my code that starts with "$added = INSERT INTO..."

Any help or suggestions are greatly appreciated.

1 Answer 1

1

You have to access to your column in the array

If your csv is something like this

Inside your while, you can access the values like:

echo $data[0] // prints 'Value 1'

So you might want to do something like...

$added = "INSERT INTO Items VALUES(".$data[0].")";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.