0

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);
3

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

  • 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

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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