Skip to content

Commit 7087a25

Browse files
dr-matt-smithwouterj
authored andcommitted
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 ..
1 parent 167e638 commit 7087a25

File tree

1 file changed

+6
-6
lines changed

1 file changed

+6
-6
lines changed

book/from_flat_php_to_symfony2.rst

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -254,9 +254,11 @@ an individual blog result based on a given id::
254254
function get_post_by_id($id)
255255
{
256256
$link = open_database_connection();
257-
$id = intval($id);
258-
$result = $link->query('SELECT created_at, title, body FROM post WHERE id = '.$id);
259-
$row = $result->fetch(PDO::FETCH_ASSOC);
257+
$query = 'SELECT created_at, title, body FROM post WHERE id=:id';
258+
$statement = $pdo->prepare($query);
259+
$statement->bindParam(':id', $id, PDO::PARAM_INT);
260+
$statement->execute();
261+
$row = $statement->fetch(PDO::FETCH_ASSOC);
260262

261263
close_database_connection($link);
262264

@@ -294,9 +296,7 @@ Creating the second page is now very easy and no code is duplicated. Still,
294296
this page introduces even more lingering problems that a framework can solve
295297
for you. For example, a missing or invalid ``id`` query parameter will cause
296298
the page to crash. It would be better if this caused a 404 page to be rendered,
297-
but this can't really be done easily yet. Worse, had you forgotten to clean
298-
the ``id`` parameter via the ``intval()`` function, your
299-
entire database would be at risk for an SQL injection attack.
299+
but this can't really be done easily yet.
300300

301301
Another major problem is that each individual controller file must include
302302
the ``model.php`` file. What if each controller file suddenly needed to include

0 commit comments

Comments
 (0)