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)?

2 Answers
2

You must use an array for your $vars, so replace

$vars = $a . ', ' .$b . ', ' . c;

with

$vars = array( $a, $b, $c );

But I would rather recommend you to use the $wpdb->insert( $table, $data, $format ) method. Then your code example could look like this:

$data   = array( 'a' => $a, 'b' => $b, 'c' => $c );
$format = array( '%s', '%s', '%s' );

if( empty( $a ) )
{
    $data   = array_slice( $data,   1, 2 );
    $format = array_slice( $format, 1, 2 ); 
} 

$wpdb->insert( $table, $data, $format );

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *