warrenfitzhenry
warrenfitzhenry

Reputation: 2299

PHP parse empty data from csv file

I'm trying to get data from a csv file line by line using PHP, and then insert into Mysql.

Some of the values in the rows of the csv file are empty, and need to be loaded as Null values into Mysql. I can't seems to check these values though. I've tried:

        if (strlen($csv[9])==0) {
            $follow_up1 = null;
        } else {
            $follow_up1 = $mysqli->real_escape_string($csv[9]);
        }

or:

    if (empty($csv[9]) {
        $follow_up1 = null;
    } else {
        $follow_up1 = $mysqli->real_escape_string($csv[9]);
    }

or:

    if (is_null($csv[9]) {
        $follow_up1 = null;
    } else {
        $follow_up1 = $mysqli->real_escape_string($csv[9]);
    }

How can I check if the cell value is empty?

Upvotes: 1

Views: 1152

Answers (3)

Adder
Adder

Reputation: 5868

If you need a string to place into an insert query, that can be the string NULL, then you need to add the single quotes at the same time:

if (empty($csv[9]) {
    $follow_up1 = "NULL"; // a string between quotes
} else {
    $follow_up1 = "'" . $mysqli->real_escape_string($csv[9]) . "'";
}

And then use $follow_up1 in the SQL without quotes

Upvotes: 0

jeromegamez
jeromegamez

Reputation: 3541

This should do:

if (trim($csv[9]) === '') {
    $follow_up1 = null;
} else {
    $follow_up1 = $mysqli->real_escape_string($csv[9]);
}

Upvotes: 1

Nicu-Cristian Vlad
Nicu-Cristian Vlad

Reputation: 98

at the second example you are missing a ")" so this might throw you an error.

if (empty($csv[9])) {
        $follow_up1 = null;
    } else {
        $follow_up1 = $mysqli->real_escape_string($csv[9]);
    }

you could also search :

$follow_up1 = $csv[9] === '' ? null : $mysqli->real_escape_string($csv[9]);

or :

 $follow_up1 = $csv[9] === "NULL" ? null : $mysqli->real_escape_string($csv[9]);

that if what you have there is an empty string .

Upvotes: 1

Related Questions