As i want to manage the NULL fields in my db and wordpress functions doesn’t allow to do so, i will need to dynamically generate a query depending on the situation. The problem is that i don’t know how to pass a variable number of fields as second argument! this is what i’ve been tr but it returns an “Empty query” error:
if ($a == '') {
$fields = 'b, c';
$placeholders = "'%s', '%s'";
$vars = $b . ', ' . c;
} else {
$fields = 'a, b, c';
$placeholders = "'%s', '%s', '%s'";
$vars = $a . ', ' .$b . ', ' . c;
}
global $wpdb;
$wpdb->show_errors();
$query = 'INSERT INTO table (' . $fields . ') VALUES (' . $placeholders . ')';
$wpdb->query($wpdb->prepare($query, $vars));
is there any way to do so (even using $wpdb->insert)?
You must use an array for your
$vars
, so replacewith
But I would rather recommend you to use the
$wpdb->insert( $table, $data, $format )
method. Then your code example could look like this:You are trying (almost) to construct the whole query and then pass it through
prepare
. That is not right.prepare
works more likesprintf
.orvsprintf
$s
. That won’t work.prepare
can be an array, and that is what I’d use here.Try this: