Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in…filetext

后端 未结 1 604
野的像风
野的像风 2020-12-01 23:05

$fields is an array that after printing gets values like:

Array ( [first_name] => Nisse [last_name] => Example [ssn] => 198306205053 [address] =>         


        
相关标签:
1条回答
  • 2020-12-01 23:27

    If you use positional parameters, the array of parameters you pass to execute() must be an ordinal array. Likewise, if you use named parameters, the array must be an associative array.

    Here's a test to confirm the behavior:

    $stmt = $db->prepare("SELECT ?, ? ,?");
    
    $params = array( 'a', 'b', 'c' );
    // OK
    if ($stmt->execute($params)) {
      print_r($stmt->fetchAll());
    }
    
    $params = array( 'A'=>'abc', 'B'=>'def', 'C'=>'ghi' );
    // ERROR!
    if ($stmt->execute($params)) {
      print_r($stmt->fetchAll());
    }
    
    $stmt = $db->prepare("SELECT :A, :B, :C");
    
    $params = array( 'a', 'b', 'c' );
    // ERROR!
    if ($stmt->execute($params)) {
      print_r($stmt->fetchAll());
    }
    
    $params = array( 'A'=>'abc', 'B'=>'def', 'C'=>'ghi' );
    // OK
    if ($stmt->execute($params)) {
      print_r($stmt->fetchAll());
    }
    

    Note that in current versions of PHP, the associative array keys don't have to be prefixed with : as @prodigitalson comments. The : prefix used to be required in array keys in older versions of PHP.

    It's also worth mentioning that I've encountered bugs and unpredictable behavior when I tried to mix positional parameters and named parameters in a single query. You can use either style in different queries in your app, but chose one style or another for a given query.

    0 讨论(0)
提交回复
热议问题