Skip to content

Instantly share code, notes, and snippets.

@vote539
Created July 22, 2013 01:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vote539/6050726 to your computer and use it in GitHub Desktop.
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.
<?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