How to do checking before importing the csv file by 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 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 database is correct but that in csv is wrong).
At the end, the php can show the message that your csv data is incorrect! Thanks! Anyone can help?

Recommended Answers

All 4 Replies

//Process the CSV file


        $row = 1;
	$handle = fopen($_FILES['file']['tmp_name'], "r");
	$data = fgetcsv($handle, 1000, ";"); //Remove if CSV file does not have column headings
	while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
              $num = count($data);


          for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";

        }

It was shown all the data in each line. If i just want the data in row 2 column 2 (specific cell), then what code should be added? Thanks!

you can try something like this:

$handle = fopen($_FILES['file']['tmp_name'], "r");
while(!feof($handle)) {
	$data = fgets($handle);
	$listing = explode(",", $data);	
	$id = $listing[0];
	$name=$listing[1];  // this is second column data.
	$telephone = $listing[2];
	$email = $listing[3];
	
	echo "id = " . $id . "<br />";
	echo "name = " . $name . "<br />";
	echo "telephone = " . $telephone . "<br />";
	echo "email = " . $email . "<br />";
	
	// connect to your db, not included:
	$sql = "update db_name set name='$name', telephone='$telephone',email='$email' where id = $id";
        // or since you said name & id
	$sql = "update db_name set name='$name', telephone='$telephone',email='$email' where id = $id and name='$name'";
	mysql_query($sql) or die (mysql_error());
	
}
// close your db connection (outside the loop);

thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.