1

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

2 Answers2

0

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. Last but not the least, Prepared statements are very useful against SQL injection if parameters are bind to it.

Faisal Mohmand
  • 155
  • 1
  • 10
  • _Prepared statements are very useful against SQL injection._ But not queries where you DONT USE Parameterized queries!!!! – RiggsFolly May 23 '16 at 23:37
  • Yes, you are right. I have written there to use Parameterized queries while using Prepared statements, otherwise in the 2nd code example the prepare statement is yet making a template for the query at that time (which is of no worth without parameters) but still logically saying that, query has been prepared there,if anyone want to execute the query later via "execute". (That's what prepare() do with or without binding parameter into it.) – Faisal Mohmand May 24 '16 at 12:15
-1

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

Community
  • 1
  • 1
Dale
  • 10,384
  • 21
  • 34