Confusion between bindValue() and bindParam()?

微笑、不失礼 提交于 2019-12-17 10:42:49

问题


I am confuse between these two functions Bindvalue() and BindParam()

  1. I read on php.net it does not escape % and _, so be careful when using LIKE. So i think BindValue() is not used when we are using LIKE query.
  2. when we using LIKE query BindParam() is used. Because as i know BindParam can escape these % and _.
  3. BindValue() doesn't gives protection against sql injection. I am not sure about this, is it true?

friends tell what i mention in these 3 points is right or wrong. i am beginner in PDO so please explain it clearly ..


回答1:


There should be no difference in how values are escaped or not escaped. bindParam differs from bindValue in that it references the variable, binding the value only when you execute the statement. bindValue takes the value immediately. To illustrate:

$stmt = $db->prepare('SELECT * FROM `table` WHERE foo = :foo');

$foo = 'foo';
$stmt->bindValue(':foo', $foo);
$foo = 'bar';

$stmt->execute();

The above executes like SELECT * FROM table WHERE foo = 'foo';

$stmt = $db->prepare('SELECT * FROM `table` WHERE foo = :foo');

$foo = 'foo';
$stmt->bindParam(':foo', $foo);
$foo = 'bar';

$stmt->execute()

The above executes like SELECT * FROM table WHERE foo = 'bar'.

It's true that neither cares about _ or % as special characters, because generally speaking they aren't special characters as far as the syntax is concerned, and the database driver is not able to analyze the context to figure out whether you mean % to be a wildcard or the actual character "%" in the context of a LIKE query.

Both protect against SQL injection.




回答2:


Well, you took it all wrong.

Bindvalue() and BindParam() are equal in either way except for the argument type.

  • Bindvalue() binds just a value, it's like a a hard copy.
  • BindParam() binds a variable, and when a variable got changed, the binded value will be changed as well.

Both of them do not escape % and _, which doesn't matter too much. Such escaping affects only reliability of the returned results, not whatever "injections".



来源:https://stackoverflow.com/questions/14413326/confusion-between-bindvalue-and-bindparam

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!