Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am not trying to use $wpdb->insert, but prepare.

Insert method will have one query string and an array which includes # of data which is not defined but will be defined for each query string keyword.

For example, "address.insert" query string defines a string of query with 3 variables when it process query such as owner_id, address_info, city.

Instead of using $owner_id, ... , $country at the $wpdb->prepare section, I am trying to pass an array holds all of variables listed in below.

Does anyone know if it is doable passing an array for prepare? It wasn't working for me when I tried.

Works

$sql = $wpdb->prepare($this->queryArray[$selectQuery], $owner_id, $address1, $address2, $city, $zip, $country);

Trying to do

$sql = $wpdb->prepare($this->queryArray[$selectQuery], $inputArray);

Here's an example code.

public function Insert($selectQuery, $inputArray)
{
    try
    {
        global $wpdb;
        $wpdb->show_errors();
        $sql = $wpdb->prepare($this->queryArray[$selectQuery], $owner_id, $address1, $address2, $city, $zip, $country);
        $result = $wpdb->query($sql);
        return $result;
    }
    catch(Exception $e)
    {
        echo $e->getMessage();
        return -1;
    }
}

Solved: This just works fine.

$sql = $wpdb->prepare($this->queryArray[$selectQuery], $inputArray);
share|improve this question

1 Answer 1

up vote 3 down vote accepted

From the Codex, 2nd parameter for the prepare() method:

(int|string|array) The value to substitute into the placeholder. Many values may be passed by simply passing more arguments in a sprintf()-like fashion. Alternatively the second argument can be an array containing the values as in PHP's vsprintf() function. Care must be taken not to allow direct user input to this parameter, which would enable array manipulation of any query with multiple placeholders. Values must not already be SQL-escaped.

So you can directly pass your input array, as long as you have same number of "%s" placeholders in your query string as the array length.

Btw in your code above the $owner_id, $address1, $address2, $city, $zip, $country variables are undefined. Did you miss extract($inputArray) ?

share|improve this answer
    
Yes, it works! It wasn't working because there was a silly typo but giving me not much info about it. Thanks a lot @One Trick Pony. The array just work as I was trying to do, edited above. –  handicop Jun 12 '12 at 5:29

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.