tell csv import script to ignore blank rows?

Posted on 16th Feb 2014 01:33 pm by admin

Hi i have the below script but i get an error if a row is blank ie a return in the csv file at the end i need to somehow tell it to skip the rows that have nothing on them:

Code: <?php
// define table name and csv file location and name

$supp_id = "15";
$pricecode = "6";
$csvupload = "../ccd/Catalogue_ZZMILGAT.csv";

// create DB connection
$host = "localhost";
$user = "user";
$pass = "pass";
$mydb = "db";
$table = "table";

$db = mssql_connect($host,$user,$pass);

// delete all old data
$sql2 = "DELETE FROM ".$table." WHERE supp_id = ".$supp_id."";

mssql_query($sql2) or die("Failed to insert to db ");

// Define DB mapping (Fill in rest of the mapping in order of appearance in CSV)
$fields = array(

// Open the CSV file
$handle = fopen($csvupload, "r") or die("Unable to open $csvupload for reading");

// Get each row's values to an array
$i = 1;
// define tab delimited or comma
while (($data = fgetcsv($handle, 512, ",")) !== FALSE) {
// First row's headers and not included, otherwise row field count must match wanted field count
if(count($data)==count($fields) && $i!=1){
$rows[] = $data;
elseif(count($data)!=count($fields)) {
die("Erroneus CSV file: incorrect field count on row $i");

// Close file handle

// Create SQL
if(count($rows)==0) die("No rows found in user file");

// Remove last comma
foreach($rows as $i => $row){
$sql = "INSERT INTO ".$table." (";
foreach($fields as $field)
$sql .= "$field,";
$sql = substr($sql,0,-1).",supp_id, date_added, PriceCode) VALUES ";
$sql .= "(";
foreach($row as $j => $value){
$value = "0";
// Quote strings, try to remove existing quotes
$value = str_replace("'","",$value);
$value = str_replace(""","",$value);
$sql .= "'$value',";

$sql = substr($sql,0,-1).",'".$supp_id."', getdate(),'".$pricecode."')"; // Remove last comma
//echo "SQL became: $sql";

mssql_query($sql) or die("Failed to insert to db ");



No comments posted yet

Your Answer:

Login to answer
110 Like 17 Dislike
Previous forums Next forums
Other forums

Warning: session_start() headers already sent error - Driving me Nuts!
I am trying my sister in laws site and I keep getting an error with my coding. I am more of a design

Format timestamp from mysql
When I tried this:
Code: date("m/d/Y H:i A", $row['timestamp'])
I got 12/31/1969 18:

Scheduler problems related to execution of a single BLT by many schedules
Hello all,

We are running several MII instances in a distibuted architecture using a sing

Multiple Do / While Statements?
I'm still very new to PHP, and running in to a problem when trying to execute a do/while loop inside

New Rolex Watches, Rolex Datejust II
[b]swiss replica watches aaa+[/b] [b][url=]swiss replica watches[/url]

Sign up to write
Sign up now if you have flare of writing..
Login   |   Register
Follow Us
Indyaspeak @ Facebook Indyaspeak @ Twitter Indyaspeak @ Google+ Indyaspeak @ Pinterest RSS