2

I was wondering if I should be using prepared statements for simple select queries?

Such as:

`SELECT * FROM `table_name`

With this, wouldn't it be better to just do:

$db->query('SELECT * FROM `table_name`');

4 Answers4

1

If the query is only run once (per script) and there are indeed no variables in it, it indeed doesn't make much of a difference whether you use prepared statements or a one-off query.

deceze
  • 510,633
  • 85
  • 743
  • 889
1

@deceze is right. but if you want to used prepared statement use something like this,

<?php
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name = ?");
if ($stmt->execute(array($_GET['name'])))       // <== passed array of parameters
{
  while ($row = $stmt->fetch()) 
  {
    print_r($row);
  }
}
?>
John Woo
  • 258,903
  • 69
  • 498
  • 492
0

As far as I think it is not a must, BUT you better do it for the integrity of the code. This simple select query (Which has no assignment) would not be able to attack.

Ruwantha
  • 2,603
  • 5
  • 30
  • 44
0
  1. If your table_name is a variable and not a hard coded item, you are protecting yourself from SQL injection.
  2. The prepared statement separates the preparation (i.e. planning) and execution.
  3. If you will be running the same query over and over again, then you are improving performance because you only plan the query once.

Performance loss of using a prepared statement over direct query for something like this, is virtually non-existent, because you open the connection either way, and the extra call that is done to execute is over the same connection.

Using * for selects if you plan to select only certain fields from a table, is likely to be as bad of a performance hit.

Ikstar
  • 153
  • 1
  • 8