If the columns are null by default, you can omit them in the INSERT
query if the values are empty. Generate the query dynamically using an array, and implode on it within your query. The keys represent the column-names, the value of the element in the array is the value to be inserted.
$columns = [];
if (!empty($var1)) {
$columns['a'] = $var1;
}
if (!empty($var2)) {
$columns['b'] = date("Y-m-d", strtotime($var2));
}
if (!empty($columns)) {
$query = "INSERT INTO abc (".implode(", ", array_keys($columns)).")
VALUES (".implode(", ", array_values($columns)).")";
}
If you can tell which database-API you're using (MySQLi or PDO), I can show you how to dynamically create the prepared statement instead, which you really should use! See How can I prevent SQL injection in PHP?
Update: Using prepared statements with MySQLi
MySQLi bindings are ordered, and using placeholders as ?
. You still generate the values in $columns
as before, but the generation of the query is slightly different.
- Use
trim(str_repeat("?, ", count($columns)), ", ")
to generate the placeholders.
- Use
str_repeat("s", count($columns))
to generate the types.
- Use the "unpacking operator"
...
to unpack all the values.
The below code assumes that the connection-object is called $mysqli
.
if (!empty($columns)) {
$column_list = implode(", ", array_keys($columns));
$bindings_list = trim(str_repeat("?, ", count($columns)), ", ");
$types_list = str_repeat("s", count($columns));
$query = "INSERT INTO abc ($column_list)
VALUES ($bindings_list)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param($types_list, ...$columns);
$stmt->execute();
$stmt->close();
}