使用命名占位符时PHP / SQL插入错误

时间:2012-02-22 14:27:40

标签: php mysql arrays pdo associative-array

我有以下PHP PDO声明:

$STH = $this->_db->prepare("INSERT INTO UserDetails (FirstName, LastName, 
            Address, City, County, PostCode, Phone, Mobile, Sex, DOB, 
            FundraisingAim, WeeksAim, LengthsAim, HearAboutID,
            MotivationID, WelcomePackID, ContactPrefID, TitleID) 
            VALUES
            (:firstName, :lastName, :address, :city, :county, :postCode, 
            :phone, :mobile, :sex, :DOB, :fundraisingAim, :weeksAim,
            :lengthsAim, :hearAbout, :motivation,
            :welcomePackPref, :contactPref, :title)");

$STH->execute($userData);

其中$userData是关联数组。我仔细检查了名字,我不明白为什么我收到以下错误:

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

我犯了什么愚蠢的错误?

3 个答案:

答案 0 :(得分:5)

您的$userData必须具有与您的对帐单绑定的完全相同的占位符,不多也不少。请参阅PDOStatement::execute documentation,该部分显示“您无法绑定多于指定值的值。”

你需要准备你的execute()参数,以准确匹配你的约束。如果正确排列数组,array_intersect_key()很容易。我通常将它包装在一个函数中,该函数也会处理前缀,如下所示:

// Adds a prefix to a name for a named bind placeholder
function prefix($name) {
    return ':'.$name;
}

// like 'prefix()', but for array keys
function prefix_keys($assoc) {
    // prefix STRING keys
    // Numeric keys not included
    $newassoc = array();
    foreach ($assoc as $k=>$v) {
        if (is_string($k)) {
            $newassoc[prefix($k)] = $v;
        }
    }
    return $newassoc;
}

// given a map of datakeyname=>columnname, and a table name, returns an
// sql insert string with named bind placeholder parameters.
function makeInsertStmt($tablename, $namemap) {
    $binds = array_map('prefix', array_keys($namemap));
    return 'INSERT INTO '.$tablename.' ('.implode(',',$namemap).') VALUES ('
    .implode(',',$binds).')';
}

// returns an array formatted for an `execute()`
function makeBindData($data, $namemap) {
    // $data assoc array, $namemap name->column mapping
    return prefix_keys(array_intersect_key($data, $namemap));
}

// example to demonstrate how these pieces fit together
function RunTestInsert(PDO $pdo, $userData) {
    $tablename = 'UserDetails';
    // map "key in $userData" => "column name"
    // do not include ':' prefix in $userData
    $namemap = array(
      'firstName'       => "FirstName",
      'lastName'        => "LastName",
      'address'         => "Address",
      'city'            => "City",
      'county'          => "County",
      'postCode'        => "PostCode",
      'phone'           => "Phone",
      'mobile'          => "Mobile",
      'sex'             => "Sex",
      'DOB'             => "DOB",
      'fundraisingAim'  => "FundraisingAim",
      'weeksAim'        => "WeeksAim",
      'lengthsAim'      => "LengthsAim",
      'hearAbout'       => "HearAboutID",
      'motivation'      => "MotivationID",
      'welcomePackPref' => "WelcomePackID",
      'contactPref'     => "ContactPrefID",
      'title'           => "TitleID",
    );
    $sql = makeInsertStmt($tablename, $namemap);
    $binddata = makeBindData($userData, $namemap);

    $pstmt = $pdo->prepare($sql);
    $pstmt->execute($binddata);
}

这样的抽象的好处是你不需要担心绑定参数本身。

答案 1 :(得分:1)

正如消息所暗示的那样,$ userData有太多或太少的条目。需要完全匹配。考虑发布$ userData的转储。

答案 2 :(得分:-1)

由于某种原因,不确定这是否是故意的,但你有这个:

EndDate = 1

在列名称的中间。

此外,您列出了18个列名,但只列出了17个值。所以错误信息是正确的。