-1

In a script I receive a variable value with GET request and I have to explode it by a delimiter but sometimes part of the string is empty. How do I declare that in the INSERT query to insert NULL if string is empty?

$statement = $db->prepare('insert into _table (column1, column2, etc.) values (?, ?, etc.)
if (isset($_GET['var']) || isset($_GET['var1'])) { 
$pieces=explode("delimeter", $var);
// $data = array($somevar, $someothervar, $pieces[0], pieces[1], etc.);
} else {
// other things to do with // $data = array($somevar, $someothervar, etc.);
}
$statement->execute($data);

Sometimes it happens that the value of $pieces[0], $pieces[1], etc is "" (quote excluded, just for reference), or so to say empty. How do I make it insert NULL in the database if any of the exploded pieces are empty? Not really sure where and how to declare the !empty check because of the isset. Current code enters blanks in the table rows instead of NULL for the empty exploded pieces. Please note that the exploded pieces are not always empty and sometimes not all of them are empty, sometimes all are empty. Depends on the case. :)

lion
  • 97
  • 2
  • 13
  • If you're going to post pseudo/unfinished code, at the very least don't introduce something that will throw off syntax highlighting. – Funk Forty Niner Sep 20 '18 at 13:34
  • check https://stackoverflow.com/questions/13867593/insert-default-into-not-null-column-if-value-is-null/13867665#13867665 – Madhur Bhaiya Sep 20 '18 at 14:08

1 Answers1

-1

This should answer your question.

Just set the value you want to insert and be NULL to null e.g $someVar = null;

In your example you might want to check if any of the values in your array are an empty string and replace them with null

foreach ($data as $key => $value) { 
    if $value === "" {
        $data[$key] = null;
    }
}
DerMolly
  • 464
  • 5
  • 17
  • Thanks for your answer! The thing is that the pieces[x] may not be always empty, or some of them may be empty, some not. If not used the var after explosion returns empty strings. How do I set it to convert to NULL for each pieces[x] if empty? Funny case. Never had that kind of thing before. – lion Sep 20 '18 at 13:35