I have the following PHP PDO statement:
$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);
Where $userData is an associative array. I’ve double checked the names and I don’t understand why I’m getting the following error:
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
What silly mistake have I made?
Your
$userDatamust have exactly the same placeholders bound by your statement, no more and no fewer. SeePDOStatement::executedocumentation, the part that says “You cannot bind more values than specified”.You need to prepare your argument to
execute()to match your binds exactly. This is easy witharray_intersect_key()if you arrange your arrays correctly. I usually wrap this in a function which will also take care of prefixing, like below:The benefit of an abstraction like this is you don’t need to worry about the bind parameters themselves.