PDO插入错误:SQLSTATE [HY093]:参数号无效:未定义参数

时间:2014-04-23 09:32:10

标签: php pdo sql-insert

我还没能找到解决我在尝试进行PDO插入时收到的错误的方法。我一直收到错误

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

这是我的代码:

    try{
        $STH = $DBH->prepare("INSERT INTO members (fname, mname, lname, gender, dob, id, nation, 
mstatus, mobile, tel, address, county, email, o_email, residence, sacco, nk_name, relationship, age, 
nk_id, nk_tel, nk_address, photo, idlink) VALUES (:fname, :mname, :lname, :gender, :dob, :id, :nation, 
:mstatus, :mobile, :tel, :address, :county, :email, :o_email, :residence, :sacco, :nk_name, :relationship, :age, 
:nk_id, :nk_tel, :nk_address, :photo, :idlink)");

这里是我添加bindValues的地方(我只是这样做,因为StackOverflow不允许使用大型代码块)

$STH->bindValue(1, $_POST['fname'], PDO::PARAM_STR);
$STH->bindValue(2, $_POST['mname'], PDO::PARAM_STR);
$STH->bindValue(3, $_POST['lname'], PDO::PARAM_STR);
$STH->bindValue(4, $_POST['gender'], PDO::PARAM_STR);
$STH->bindValue(5, $_POST['dob'], PDO::PARAM_STR); 
$STH->bindValue(6, $_POST['id'], PDO::PARAM_STR);
$STH->bindValue(7, $_POST['nation'], PDO::PARAM_STR);
$STH->bindValue(8, $_POST['mstatus'], PDO::PARAM_STR); 
$STH->bindValue(9, $_POST['mobile'], PDO::PARAM_STR);
$STH->bindValue(10, $_POST['tel'], PDO::PARAM_STR);
$STH->bindValue(11, $_POST['address'], PDO::PARAM_STR);
$STH->bindValue(12, $_POST['county'], PDO::PARAM_STR);
$STH->bindValue(13, $_POST['email'], PDO::PARAM_STR);
$STH->bindValue(14, $_POST['o_email'], PDO::PARAM_STR);
$STH->bindValue(15, $_POST['residence'], PDO::PARAM_STR);
$STH->bindValue(16, $_POST['sacco'], PDO::PARAM_STR);
$STH->bindValue(17, $_POST['nk_name'], PDO::PARAM_STR); 
$STH->bindValue(18, $_POST['relationship'], PDO::PARAM_STR);
$STH->bindValue(19, $_POST['age'], PDO::PARAM_INT);
$STH->bindValue(20, $_POST['nk_id'], PDO::PARAM_STR);
$STH->bindValue(21, $_POST['nk_tel'], PDO::PARAM_STR);
$STH->bindValue(22, $_POST['nk_address'], PDO::PARAM_STR);
$STH->bindValue(23, $_POST['photo'], PDO::PARAM_STR);
$STH->bindValue(24, $_POST['idlink'], PDO::PARAM_STR);

$STH->execute();

}
    catch (PDOException $e) {
    echo "DataBase Error: The member could not be added.<br>".$e->getMessage();
    } catch (Exception $e) {
        echo "General Error: The member could not be added.<br>".$e->getMessage();  
    }

1 个答案:

答案 0 :(得分:3)

有两种方法可以修复它们。(选择任何一种情况,你不能同时使用它们)

案例1:命名占位符

$STH->bindValue(':fname', $_POST['fname'], PDO::PARAM_STR);
$STH->bindValue(':mname', $_POST['mname'], PDO::PARAM_STR);
$STH->bindValue(':lname', $_POST['lname'], PDO::PARAM_STR);
//...

//.. so on..

案例2:问号占位符

try{
        $STH = $DBH->prepare("INSERT INTO members (fname, mname, lname, gender, dob, id, nation, 
mstatus, mobile, tel, address, county, email, o_email, residence, sacco, nk_name, relationship, age, 
nk_id, nk_tel, nk_address, photo, idlink) VALUES (?,?,?,?,?,

 // .. so on..  (note the ? symbols...)