Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

php - Using PDO Prepared Statement and Incrementing a column value

I've read this thread: Issues incrementing a field in MySQL/PHP with prepared statements but didn't see the answer to my problem.

PDOStatement Object
(

    [queryString] => UPDATE user_alerts SET notif = ? + 2 WHERE ( user_id = ? )   

)

$stmt->execute( array( 'notif', '1' ) );

As far as I can tell, all this is correct.

When the above code executes, it sets the notif column equal to 2 irregardless of what the value of the notif column is. It's as if the SQL is reading like SET notif = 2 instead of SET notif = notif + 2

I haven't been able to figure it out and would really appreciate help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using parameters is not just a simple text replacement. You can't replace a column name with a parameter. MySQL will interpret your query as if you had written this:

UPDATE user_alerts SET notif = 'notif' + 2 WHERE ( user_id = ? ) 

The string 'notif' is converted to zero for the addition.

Try this query instead:

UPDATE user_alerts SET notif = notif + 2 WHERE ( user_id = ? )   

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...