【问题标题】:Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number警告:PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number
【发布时间】:2015-11-17 09:43:00
【问题描述】:

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

我有 3 个文件来散文 INSERT 查询: 1.控制器.php 2.模块.php 3.查询.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)"
};

有什么问题?

【问题讨论】:

    标签: php mysql pdo


    【解决方案1】:

    您正在构建 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);
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-22
    • 2015-07-07
    • 2023-03-18
    • 1970-01-01
    相关资源
    最近更新 更多