I have an array that is returned from an API although some keys/values are not present all of the time.
example array
Array
(
[example0] => data
[example1] => data
[example2] => data
[example3] => data
)
Now if I use a query such as below
$dbh = $this->database->prepare("INSERT INTO table(example0, example1, example2, example3)VALUES(:example0, :example1, :example2, :example3)");
$dbh->execute(array(
"example0" => $data['example0'],
"example1" => $data['example1'],
"example2" => $data['example2'],
"example3" => $data['example3']
));
It will work fine. But when the API returns an array like
Array
(
[example0] => data
[example1] => data
[example3] => data
)
It will cause an error due to a value not being set, is there a way to just have it enter nothing into the column rather than throw an error? I am using a really big query for this so writing an if/else for each value would not be a good idea (in my opinion, for performance wise)
You have to check if the key is set and eventually is there is a value:
if(isset($array['your_key']) && !empty($array['your_key'])) { }
I cannot make it clear from your code but validate everything before you use it in a query.
[Edit] Example:
$keys = array('example1', 'example2', 'example3', 'example4');
$use_in_query = array();
foreach($keys as $key)
{
if(isset($array[$key]) && !empty($array[$key])) $use_in_query[$key] = $array[$key];
}
Now you can use the $use_in_query var in your query.
$dbh->execute($use_in_query);
[/Edit]