简体   繁体   中英

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined'

I've read a bunch of threads discussing this problem and I can't find what's wrong with my code.I have an array:

    $insert_arr["$key"]['customer']["$cust->Company"]['cpq_id'] = "$cust->CustomerId";
    $insert_arr["$key"]['customer']["$cust->Company"]['shop_cart_id'] = "$cust->ShopCartId";
    $insert_arr["$key"]['customer']["$cust->Company"]['user_id'] = "$cust->UserId";
    $insert_arr["$key"]['customer']["$cust->Company"]['company'] = "$cust->Company";
    $insert_arr["$key"]['customer']["$cust->Company"]['crm_id'] = empty("$cust->CRMAccountId") ? 0 : "$cust->CRMAccountId";

A bit later, I have:

$q_customer = 'insert into customers
                                 (
                                   cpq_id, 
                                   shopping_cart_id,
                                   user_id,
                                   company_name,
                                   crm_id
                                  )
                                  values (?, ?, ?, ?, ?)';
$sc = $db2->prepare($q_customer);

And later still:

foreach ($insert_arr as $id => $arr) {
    foreach($arr['customer'] as $c) {
            $sc->execute($c);
    }
}

And I always get the error referenced in the title. I've never used PDO before, and I can't figure out what's wrong. Help please!

You have to bind your parameters before to call the execute method. Your array is also a 3rd dimension type, so you will need to add a foreach.

Like this :

foreach ($insert_arr as $id => $arr) {
    foreach($arr['customer'] as $c) {
        $params = array();
        foreach($c as $param => $value) {
            $params[] = $value;
        }
        $sc->execute($params);
    }
}
$sc->execute();

If you want to use an associative array as the argument to execute() , you have to use named placeholders, not ? . The placeholder names must match the array indexes.

$q_customer = 'insert into customers (cpq_id, shopping_cart_id, user_id, company_name, crm_id) values (:cpq_id, :shop_cart_id, :user_id, :company, :crm_id)';
$sc = $db2->prepare($q_customer);
foreach ($insert_arr as $id => $arr) {
    foreach($arr['customer'] as $c) {
            $sc->execute($c);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM