Jump to content

Recommended Posts

I have a script to import a daily generated csv file to a database, and it works fine for all other the other files, but on this file I am running into a problem of it reporting back "Column count doesn't match value count at row 1" on some of the rows. There are 20 fields in the database, and some rows have the required 20 fields, but others are missing the very last field, and there is only 19 fields in that row. Is there anything I can do to fix this problem, without adding another field to the file?

 

Basically I just want it to forget the last field in the row, if it's not there in the file, and just go to the next row. Is this possible?

 

Here is my code:

 

$conn = mysql_connect($databasehost, $databaseusername, $databasepassword);
if (!$conn) {
	echo mysql_error();
	exit;
}
if (!mysql_select_db($databasename)) {
	echo mysql_error();
	exit;
} else {
$sql2 = "DELETE FROM `".$databasetable."`";
    mysql_query($sql2);
}
$fcontents = file($csvfile);
for($i=0; $i<sizeof($fcontents); $i++) {
	$line = trim($fcontents[$i]);		
	$arr = explode("\t", $line);
	$arr = preg_replace( "`[^a-zA-Z0-9+&@#%=~_|!:/\*,.( ]`", "", $arr);
	$sql = "INSERT INTO $databasetable VALUES ('". implode("','", $arr) ."')";
	mysql_query($sql);
	echo $sql ."<br>\n";
		if(mysql_error()) {
			echo mysql_error() ."<br>\n";
		}
}
?>

After you explode the line, you can get a count of the number of elements. If the missing field is always the last one, you can add a blank/default value onto the end of the exploded elements.

 

Alternatively, you should already be listing the field names in the query. When one field is missing, you could build a query that does not contain that field name and simply leave that field and missing-value out of the query.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.