Andy Andy - 3 months ago 15
MySQL Question

Can you omit PDO prepare if there's no placeholder/dynamic data in a query?

I'm working on an application at the moment that uses PDO with a MySQL database.

I'm seeing some queries, which are just very simple

statements, e.g.


The code does not use
, for example:

$sql = "SELECT * FROM " . $this->table . " ORDER BY name ASC";
$stmt = $this->db->query($sql);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results;

Is it ok to do this, i.e. without using prepare, if there's no placeholders in the query?

The reason I've asked this is because according to the documentation it says

The SQL statement can contain zero or more named (:name) or question mark (?) parameter markers

which makes me wonder why you'd use this in the case of having no (zero) parameter markers?


Yes, because the use of prepared statements have 2 main causes:

  1. Enhance running the same query with different parameters.
  2. Prevent sql injection by separating sql code from the parameters.

Since you have no parameters that could be handled by a prepared statement (table names cannot be a parameter), you do not gain anything by pushing the query through as a prepared statement.

You still need to make sure that whatever is returned by $this->table will not cause any issues with the generated sql code.