PDO错误:参数号无效:绑定变量数与令牌数不匹配

时间:2015-06-20 19:30:11

标签: php pdo

我在执行以下代码时收到错误无效参数编号:绑定变量数与令牌数不匹配

$query = " 
    SELECT 
        project_id, 
        product_name,
        product_description,
        imagelg_url,
        product_url, 
        amazon_price,
        your_price,
        review_value,
        coupon 
    FROM project 
    WHERE
        project_id = :id
"; 

$update = " 
    UPDATE project
    SET  
        product_name = :productname, 
        product_description = :productdescription,
        imagelg_url = :imagelgurl,
        product_url = :producturl,
        amazon_price = :amazonprice,
        your_price = :yourprice, 
        review_value = :reviewvalue,
        coupon = :coupon
    WHERE
        project_id = :id
";

// Here we prepare our tokens for insertion into the SQL query. 
//
$query_params = array(
    ':productname' => $_POST['productname'],
    ':productdescription' => $_POST['productdescription'], 
    ':imagelgurl' => $_POST['imagelgurl'], 
    ':producturl' => $_POST['producturl'],
    ':amazonprice' => $_POST['amazonprice'],
    ':yourprice' => $_POST['yourprice'],
    ':reviewvalue' => $_POST['reviewvalue'],
    ':coupon' => $_POST['coupon']  
); 

try 
{ 
    // These statements run the query against your database table. 
    $stmt = $db->prepare($query); 
    $stmt->bindParam(':id', $id, PDO::PARAM_INT); 
    $stmt->execute();
    $uproject = $db->prepare($update); 
    $uproject->bindParam(':id', $id, PDO::PARAM_INT);
    $up = $uproject->execute($query_params);

} 

我在以下代码中分配$id

$path_parts = explode("/", $_SERVER['REQUEST_URI']);
$id = array_pop($path_parts);

非常感谢任何帮助。提前谢谢!

1 个答案:

答案 0 :(得分:3)

您收到无效参数编号错误,因为您正在使用bindParam()并将数组传递到execute()。将任何数组传递给execute()将擦除并替换以前的任何绑定。

您需要通过bindParam()execute()绑定数据,但不能通过两者绑定。

要解决此问题,请将$query_params作业更改为以下内容:

$query_params = array(
    ':id' => $id,
    ':productname' => $_POST['productname'],
    ':productdescription' => $_POST['productdescription'], 
    ':imagelgurl' => $_POST['imagelgurl'], 
    ':producturl' => $_POST['producturl'],
    ':amazonprice' => $_POST['amazonprice'],
    ':yourprice' => $_POST['yourprice'],
    ':reviewvalue' => $_POST['reviewvalue'],
    ':coupon' => $_POST['coupon']  
); 

然后将更新查询更改为以下内容:

$update = " 
    UPDATE project
    SET  
        id = :id,
        product_name = :productname, 
        product_description = :productdescription,
        imagelg_url = :imagelgurl,
        product_url = :producturl,
        amazon_price = :amazonprice,
        your_price = :yourprice, 
        review_value = :reviewvalue,
        coupon = :coupon
    WHERE
        project_id = :id
";

最后,从更新查询的PDO设置中删除此行:

$uproject->bindParam(':id', $id, PDO::PARAM_INT);