Created
July 22, 2013 01:22
-
-
Save vote539/6050726 to your computer and use it in GitHub Desktop.
Example implementation of inserting default values to SQLite fields given null values without changing your SQLite statement query.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// the name of your table | |
$table = "foobar"; | |
// an array of your field names with default values | |
$fields = array( | |
"foo" => 5, | |
"bar" => "(date(now))" | |
); | |
$field_names = array_keys($fields); | |
// the data you want to insert | |
$data = array( | |
"foo": 16 | |
// leave bar null to insert default value | |
); | |
// prepare the query | |
$insert_q = sprintf("INSERT INTO $table (%s) VALUES (%s)", | |
implode(", ", $field_names), | |
implode(", ", array_map("coalesce", $field_names)) | |
); | |
$stmt = $db->prepare($insert_q); | |
// bind values to the query | |
foreach($field_names as $field){ | |
$value = @$data[$field]; | |
$value_param = add_colon($field); | |
if(empty($value)){ | |
$stmt->bindValue($value_param, null, PDO::PARAM_NULL); | |
}else{ | |
$stmt->bindValue($value_param, $value); | |
} | |
} | |
// execute the statement | |
$stmt->execute(); | |
// coalesce mapping function | |
function coalesce($field){ | |
global $fields; | |
$default = @$fields[$field]; | |
if(!empty($default)){ | |
return "coalesce(:$field, ".$default.")"; | |
}else{ | |
return ":$field"; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment