From 550fbe07ab4f91d3c84a33adce6eca146dd26cc0 Mon Sep 17 00:00:00 2001 From: Roy Ronalds Date: Wed, 7 Jan 2015 14:48:07 -0500 Subject: [PATCH] PHP and UTF-8: Clarified magic numbers, escape to html with an example function for UTF-8, moved to PDO named bindings. --- _posts/05-05-01-PHP-and-UTF8.md | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/_posts/05-05-01-PHP-and-UTF8.md b/_posts/05-05-01-PHP-and-UTF8.md index 00fdc05..fd705bc 100644 --- a/_posts/05-05-01-PHP-and-UTF8.md +++ b/_posts/05-05-01-PHP-and-UTF8.md @@ -76,10 +76,14 @@ The historic approach to doing that was to include the [charset `` tag](ht prepare('insert into ElvishSentences (Id, Body) values (?, ?)'); -$handle->bindValue(1, 1, PDO::PARAM_INT); -$handle->bindValue(2, $string); +$handle = $link->prepare('insert into ElvishSentences (Id, Body, Priority) values (default, :body, :priority)'); +$handle->bindParam(':body', $string, PDO::PARAM_STR); +$priority = 45; +$handle->bindParam(':priority', $priority, PDO::PARAM_INT); // explicitly tell pdo to expect an int $handle->execute(); // Retrieve the string we just stored to prove it was stored correctly -$handle = $link->prepare('select * from ElvishSentences where Id = ?'); -$handle->bindValue(1, 1, PDO::PARAM_INT); +$handle = $link->prepare('select * from ElvishSentences where Id = :id'); +$id = 7; +$handle->bindParam(':id', $id, PDO::PARAM_INT); $handle->execute(); // Store the result into an object that we'll output later in our HTML +// This object won't kill your memory because it fetches the data Just-In-Time to $result = $handle->fetchAll(\PDO::FETCH_OBJ); -header('Content-Type: text/html; charset=UTF-8'); +// An example wrapper to allow you to escape data to html +function escape_to_html($dirty){ + echo htmlspecialchars($dirty, ENT_QUOTES, 'UTF-8'); +} + +header('Content-Type: text/html; charset=UTF-8'); // Unnecessary if your default_charset is set to utf-8 already ?> @@ -125,7 +137,7 @@ header('Content-Type: text/html; charset=UTF-8'); Body); // This should correctly output our transformed UTF-8 string to the browser + escape_to_html($row->Body); // This should correctly output our transformed UTF-8 string to the browser } ?>