警告:PDOStatement :: execute():SQLSTATE [HY093]:参数号无效:绑定变量数与数字不匹配

时间:2015-11-17 09:43:01

标签: php mysql pdo

在阅读了有关HY093的所有其他问题后,我无法弄清楚导致错误的原因。

我有3个文件来修改INSERT查询: controller.php 2. module.php 3. query.php

controller.php

$this->ModelProduct = new ModelProduct($this->db);
$param_new = "':code' =>124,':name' =>".$_POST['post_name']."";
$so_result = $this->ModelProduct->AddNew($param_new);

module.php

define('tbl_all_product','product');
define('field_product','code,name');
define('value_product',':code,:name');
function AddNew($param_new)
{
$insert = $this->insert(tbl_all_product,field_product,value_product,$param_new);
}

query.php

public function insert($tbl, $field, $val, $param_new)
    {
        $sql = "INSERT INTO ".$tbl." (".$field.") VALUES (".$val.")";
        $query = $this->db->prepare($sql);
        $query->execute(array($param_new));
    }

调试后的这个信息

$tbl = "product";

$field = "code,name";

$val = ":code,:name";

$param_new = "':code' => 124,':name' => DELL";

$sql = "INSERT INTO product (code,name) VALUES (:code,:name)";

$query = PDOStatement#10 {
    "queryString" => "INSERT INTO product (code,name) VALUES (:code,:name)"
};

问题是什么?

1 个答案:

答案 0 :(得分:0)

您正在构建param_new错误,这是

的原因
$_POST['post_name'] = 'someName';

$param_new = "':code' =>124,':name' =>".$_POST['post_name']."";

print_r(array($param_new));

/*output
Array
(
    [0] => ':code' =>124,':name' =>someName
)
*/

这是您最终传递给execute()的内容,array包含一个逗号分隔字符串的单个元素。

从头开始构建param_new数组:

$_POST['post_name'] = 'someName';

$param_new = array(':code' => 124,':name' => $_POST['post_name']);

print_r($param_new);

/*output
Array
(
    [:code] => 124
    [:name] => someName
)
*/

并将其原样传递给execute,而不是将其封装在另一个数组中

$query->execute($param_new);