0

How to do checking before importing a CSV file in PHP?

I have a CSV file which contains the information with the columns id, name, telephone, email and have the database with the same columns. I have the PHP file which can import the CSV file into the database.

Now, I want to update the information by batch, how can I match the id, name between CSV file and database so as to avoid wrong data input (suppose the data in the database is correct but that in the CSV it is wrong).

At the end, the PHP can show the message that your CSV data is incorrect! Thanks! Anyone can help?

Ben
  • 54,723
  • 49
  • 178
  • 224
sreejith
  • 68
  • 7

1 Answers1

0

You can do this as follows:

  • Read your CSV using fread() and filesize()
  • explode() the data, probably using linebreak (\n)
  • Loop through each line of data with foreach
  • Explode each line, probably using comma (,)
  • Test each index of that array with preg_match() and a regex pattern to make sure it meets your requirements
  • Query your database with something like this (in PHP, untested)

    $query = "UPDATE yourtable SET name='".$name."' WHERE id='".$id."'";


Make sure your query is santized using PDO or similar, to avoid SQL injection at all times.

That last bullet point is the key to your question, I think. You'll need to read about UPDATE and INSERT SQL queries - here's a question that may help: Mysql function: Insert if not exist or updated

You haven't included any code or a starting point in your original question, so I can't help you with the specifics, but I'm sure you can research this yourself. I'd say it's easy-intermediate difficulty.

Community
  • 1
  • 1
Ben
  • 54,723
  • 49
  • 178
  • 224