From 065dd3a3d49853eca691fb98003fb086a85b81c6 Mon Sep 17 00:00:00 2001 From: Matt Smith Date: Mon, 20 Jun 2016 12:54:31 +0100 Subject: [PATCH] use PDO prepared statement - avoid straw man I suggest demonstrating decent PDO code, through the use of a prepared statement rather than setting up a 'straw man' of concatenating _GET['id'] for form an SQL string there are very strong arguments for using Doctrine and Symfony etc. - no need to write bad PDO code to artificially strengthen the MVC argument .. matt .. --- book/from_flat_php_to_symfony2.rst | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/book/from_flat_php_to_symfony2.rst b/book/from_flat_php_to_symfony2.rst index 28ba62cf284..ff0b0d48a69 100644 --- a/book/from_flat_php_to_symfony2.rst +++ b/book/from_flat_php_to_symfony2.rst @@ -254,9 +254,11 @@ an individual blog result based on a given id:: function get_post_by_id($id) { $link = open_database_connection(); - $id = intval($id); - $result = $link->query('SELECT created_at, title, body FROM post WHERE id = '.$id); - $row = $result->fetch(PDO::FETCH_ASSOC); + $query = 'SELECT created_at, title, body FROM post WHERE id=:id'; + $statement = $pdo->prepare($query); + $statement->bindParam(':id', $id, PDO::PARAM_INT); + $statement->execute(); + $row = $statement->fetch(PDO::FETCH_ASSOC); close_database_connection($link); @@ -294,9 +296,7 @@ Creating the second page is now very easy and no code is duplicated. Still, this page introduces even more lingering problems that a framework can solve for you. For example, a missing or invalid ``id`` query parameter will cause the page to crash. It would be better if this caused a 404 page to be rendered, -but this can't really be done easily yet. Worse, had you forgotten to clean -the ``id`` parameter via the ``intval()`` function, your -entire database would be at risk for an SQL injection attack. +but this can't really be done easily yet. Another major problem is that each individual controller file must include the ``model.php`` file. What if each controller file suddenly needed to include