1

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?

4
  • How do you parse your data? What exactly marks it as "empty"? Commented Jul 4, 2018 at 12:55
  • Can you show the content of $csv ? Commented Jul 4, 2018 at 12:56
  • 4
    Please show us a var_dump($csv) Commented Jul 4, 2018 at 12:57
  • 2
    It seems you are concatenating an sql query from your variable names. Setting a variable to null will then not write a null value to the database, as you would need to put the string NULL without quotes into the query. Instead you should use prepared statements, then you can pass null values, and also get rid of the real_escape_string, and be save(r) against sql injection. Commented Jul 4, 2018 at 13:05

3 Answers 3

1

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 .

Sign up to request clarification or add additional context in comments.

Comments

1

This should do:

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

Comments

0

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

2 Comments

this is correctly inserting empty values as NULL, but valid values ('else') as number 0... any ideas?
ah i made it wrong. too much java coding .. Need to concatenate string with a dot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.