简体   繁体   English

这两个代码有什么区别

[英]What is the difference between these two codes

I coded these two blocks of code, but they seem to do the same. 我对这两个代码块进行了编码,但是它们似乎做的相同。 I don't understand when you should use each one of these. 我不知道您何时应该使用其中的每一种。

$query= $db->query("SELECT * FROM forum_table WHERE forum_id = '$id'");

and

$sql="SELECT * FROM forum_table WHERE forum_id = '$id'";
if ($query = $db->prepare($sql))
$query->execute();

I don't get how those differ 我不知道这些有什么不同

Well, In case of 好吧,如果

$query= $db->query("SELECT * FROM forum_table WHERE forum_id = '$id'");

This is very simple and known to all, simple a query executing directly as it is, no extra magic in it. 这是非常简单且众所周知的,它是直接按原样执行的查询,没有多余的魔力。

$sql="SELECT * FROM forum_table WHERE forum_id = '$id'";
if ($query = $db->prepare($sql))
$query->execute();

While in your second piece of code you have used the same query but you have prepare the query before executing (which you are not doing the right way, that is you are not leaving the placeholders to bind parameters to it,which is what the recommended and purposeful way of using prepared statements.), By making placeholders in prepared statements for binding parameters to it later prepare actually make a template before actual execution of the query which helps in many ways. 在第二段代码中,您使用了相同的查询,但是在执行之前已准备好查询(这不是正确的方法,即您没有让占位符将参数绑定到该占位符,因此建议以及通过使用准备好的语句中的占位符将参数绑定到预留位置的方式,稍后在实际执行查询之前实际准备好一个模板,这在很多方面都有帮助。 Prepared statements reduces parsing time as the preparation on the query is done only once (although the statement is executed multiple times). 准备的语句减少了解析时间,因为对查询的准备仅执行一次(尽管该语句执行了多次)。 Note: It is best practice to bound parameters into the prepare statement so that if the query has to run multiple time with different parameters.Only Bound parameters minimize bandwidth to the server as you would need to send only the parameters each time, and not the whole query. 注意:最佳做法是将参数绑定到prepare语句中,这样,如果查询必须使用不同的参数多次运行。只有绑定参数可以最大程度地减少服务器的带宽,因为您每次只需要发送参数,而不是每次发送参数。整个查询。 Last but not the least, Prepared statements are very useful against SQL injection if parameters are bind to it. 最后但并非最不重要的一点是,如果将参数绑定到SQL注入上,则Prepared语句非常有用。

For a start both of those statements are exactly the same so there is literally no difference. 首先,这两个语句完全相同,因此实际上没有区别。

There is a hint at something very different going on with the second block. 暗示第二个块发生了非常不同的事情。

prepared statements 准备好的陈述

As for when to use one over the other.. always use prepared statements 至于何时使用另一个..总是使用准备好的语句

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM