Reputation: 11
I´ve been fighting with this problem for the past hour and am about to jump out of the window. I´m trying to do an update query with a variable number of arguments: The data will come through a form but some fields (surName2 and email) are optional, so they will only be included in the query if the user fills them with data.
So I check if they're set and if so modify the query through the string $strFields, then add them to the $pdo query with bindValue(). However when I run this I get an error message saying that the number of bound parameters doesn't match those in the query. I just can't find what I'm doing wrong, all 6 variables have data and all binds are being executed but it just won't work:
$strFields = '';
if (isset($_POST['surName2'])) $strFields .= ', surName2=:surName2';
if (isset($_POST['email'])) $strFields .= ', email=:email';
$stmt = $pdo->prepare('UPDATE users SET userName=:userName, name=:name, surName1:=surName1'.$strFields.' WHERE user_id=:user_id');
$stmt->bindValue(':userName', $_POST['userName']);
$stmt->bindValue(':name', $_POST['name']);
$stmt->bindValue(':surName1', $_POST['surName1']);
if (isset($_POST['surName2'])) $stmt->bindValue(':surName2', $_POST['surName2']);
if (isset($_POST['email'])) $stmt->bindValue(':email', $_POST['email']);
$stmt->bindValue(':user_id', $_POST['user_id']);
$stmt->execute();//Throws the error
Upvotes: 0
Views: 1404
Reputation: 389
you have a syntax error on this line
$stmt = $pdo->prepare('UPDATE users SET userName=:userName, name=:name, surName1:=surName1'.$strFields.' WHERE user_id=:user_id');
for surName1 you have the ":" on the wrong side of the equal sign. Just change it to this
$stmt = $pdo->prepare('UPDATE users SET userName=:userName, name=:name, surName1=:surName1'.$strFields.' WHERE user_id=:user_id');
Upvotes: 2