开发者

PHP PDO: prepare statement question

开发者 https://www.devze.com 2023-02-05 07:02 出处:网络
Yes. So I am using PDO lib to connect and communicate with the database (MySQL) So now it looks like this when i example what to update \"bla\" column:

Yes. So I am using PDO lib to connect and communicate with the database (MySQL)

So now it looks like this when i example what to update "bla" column:

$sql = $connect->prepaer("UPDATE users SET bla='bla' WHERE id = $USER AND age =:age");
$sql->bindValue(":age", $age);
$sql->execute();

Now if you can see I have binded the value :age only and not $USER.

I have binded all my other values except $USER, in all my other queries too.

$USER is the user id you are logged in with.

I wonder if i can protect the $USER variable, if there like exists some kind of a escape string to this 开发者_运维百科like you could do with mysql_* (mysql_real_escape_string) ?.

Else i would need to edit all my queries, and add bindValue(:user, $USER)...


Well, you probably can use any of the escape functions and methods available, but the question is: why? Sure, it might be a hassle to find all your querys, but i'd say it's a real strange thing to half-parameterize your queries. Just add the bind, please ;)

That said, what is the problem with mysql_real_escape_string()? If you're really going for the quick-hack, just add that to your string building and you can play :).

But again, just put in the effort to add the bind. please? Future you will thank you.


It's worth going through changing the user anyway to make it consistent. It may be extra work, but it'll be worth it in the long run.

Also, just incase you don't know - you can pass in an array of parameters to the Execute function rather than using bindValue(). I personally have a wrapper database class, so my update call looks like this:

$db->Update("UPDATE users SET bla=? WHERE id=? AND age=?", array('bla', $USER, age));

Looks much neater IMO.

Then in my class I'm just calling prepare on the SQL and Execute on the array parameter.


PDO:quote(), but the best you can do is binding this value too.

0

精彩评论

暂无评论...
验证码 换一张
取 消