带参数数组的PDO Prepared语句

时间:2014-04-16 19:21:27

标签: php sql pdo

我被困住了。我花了两天时间查看我能找到的所有参考资料,但我无法弄清楚为什么这不起作用!我收到错误:"从空值创建默认对象。" Bellow是我的SQL语句和我的参数数组。

    $sql_insert = "
    INSERT INTO vrm_vrd_submission_tbl (vrm_vrd_nmbr_id, vrm_vrd_sub_type_id, vrm_vrd_sub_date, vrm_vrd_min_form_date, vrm_vrd_sub_quantity, county_id, pers_emp_pre_id, election_general_info_id ,vrm_vrd_sub_submitter_name, vrm_vrd_compliance_rules_id)
    VALUES(:vrm_vrd_nmbr_id,
   :vrm_vrd_sub_type_id,
   :vrm_vrd_sub_date,
   :vrm_vrd_min_form_date,
   :vrm_vrd_sub_quantity,
   :county_id,
   :pers_emp_pre_id,
   :election_general_info_id,
   :vrm_vrd_sub_submitter_name,
   :vrm_vrd_compliance_rules_id)
   ";

    $sql_parms=array(":vrm_vrd_nmbr_id"=>$vrm_vrd_nmbr_id, ":vrm_vrd_sub_type_id 
    "=>$data['vrm_vrd_sub_type_id'], 
    ":vrm_vrd_sub_date"=>trim($data['vrm_vrd_sub_date']), 
    ":vrm_vrd_min_form_date"=>trim($data['vrm_vrd_min_form_date']), 
    ":vrm_vrd_sub_quantity"=>trim($data['vrm_vrd_sub_quantity']), ":county_id 
    "=>$data['county_id'],":pers_emp_pre_id "=>$data['pers_emp_pre_id'], 
    ":election_general_info_id"=>$election_general_info_id, 
    ":vrm_vrd_sub_submitter_name"=>$vrm_vrd_sub_submitter_name, 
    ":vrm_vrd_compliance_rules_id"=> $vrm_vrd_compliance_rules_id);

    $ret_val=$db->db_bound_query($sql_insert, $sql_parms);

在我的数据库类中调用的方法:

    public function db_bound_query($qry_str, $parms_array){
            $log = new error_log_class;
            $db_conn = self::_connect();

            if(!$exec_str= $db_conn->prepare($qry_str)){    
            $log->save_to_log($qry_str,__LINE__,__FILE__,"Failed to perpare.");     
            }

            $val="";
            foreach($parms_array as $parm ->$val){
               $exec_str->bindParam($parm,$val);
            }       

            $res=$exec_str->execute();

            $results= $exec_str->fetchAll(PDO::FETCH_ASSOC);    
      }

编辑: 我把这个方法更改为@iamsleepy和@MrCode提供的以下内容。但是我收到了我最初追逐的错误,这是"无效的参数编号"。

    public function db_bound_query($qry_str, $parms_array){
            $log = new error_log_class;
            $db_conn = self::_connect();

            if(!$exec_str= $db_conn->prepare($qry_str)){    
                $log->save_to_log($qry_str,__LINE__,__FILE__,"Failed to perpare.");     
            }

            $res=$exec_str->execute($parms_array );

            $results= $exec_str->fetchAll(PDO::FETCH_ASSOC);    

            return $results;
    }

1 个答案:

答案 0 :(得分:1)

此参数名称的末尾有一个空格:

":pers_emp_pre_id "=>$data['pers_emp_pre_id']
                 ^ here

应该是:

":pers_emp_pre_id"=>$data['pers_emp_pre_id']