如何在主键上绑定值?
是否建议在主键上绑定值?
主键值来自数据库结果。
注意:它不与 GET/POST 查询链接。
例如:
$SQL2 = "SELECT storeID FROM orders limit 1"
$q = $db->prepare($SQL);
$q->execute();
$row = $q->fetch(PDO::FETCH_ASSOC);
$PrimaryKey = $row['storeID'];
$SQL2 = "SELECT * FROM store WHERE storeID= :storeID"
$q2 = $db->prepare($SQL);
$q2->bindValue(":storeID", $PrimaryKey);
Is it recommended to bindValue on a primary key?
primary key value come from database result.
Note: It is not linked with GET/POST query.
For example:
$SQL2 = "SELECT storeID FROM orders limit 1"
$q = $db->prepare($SQL);
$q->execute();
$row = $q->fetch(PDO::FETCH_ASSOC);
$PrimaryKey = $row['storeID'];
$SQL2 = "SELECT * FROM store WHERE storeID= :storeID"
$q2 = $db->prepare($SQL);
$q2->bindValue(":storeID", $PrimaryKey);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这更多的是个人喜好。在上面的情况下,当你的结果的数据类型是像 PK 或其他 int 值这样的整数时,我从不执行 bindValue 而是直接连接,例如:
$sql = 'SELECT * FROM store WHERE storeID=' 。 $row['storeID'];
$result = $db->prepare($sql)->execute()->fetch(PDO::FETCH_ASSOC);
只是因为它更短而且可能更快一些。但不要为这种过早的微优化而烦恼,如果你有总是使用bindValue的习惯,它根本不会影响你的性能。但是,如果您认为将其连接起来更干净,那么在这些情况下不存在安全缺陷,所以就这样做吧。
It is more of a personal preference. In situations like the above, when you that the data type of the result is integer like PK or other int value, I never do bindValue but directly concatenate, eg:
$sql = 'SELECT * FROM store WHERE storeID=' . $row['storeID'];
$result = $db->prepare($sql)->execute()->fetch(PDO::FETCH_ASSOC);
Just because its shorter and probably bit faster. But don't bother with such premature micro optimizations, if you have the practice of always using bindValue, it will not affect your performance at all. However if it looks cleaner to you to have it concatenated, there is no security flaw in those situations, so go for it.
考虑到它的开销并不大,所以可以使用它。您可以使用
?
表示法将其缩短。Considering it's not that overhead yes use it. You can make it shorter with the
?
notation.