Hello,
I am a training developer in .NET and web 2.0 technologies and this one is an exercise from one of our first lessons in PHP: accessing a MySQL database from a PHP script.
The problem I've encountered is that while database is thought to be in Unicode (i.e. the values contain accented characters, as this exercise is in French), the PHP script result in garbage characters (actually just one, a enlongated rectangle).
The exercise consists of a PHP script and a MySQL database with two tables where the script queries all entry data from one column in just one table (so no joins necessary).
The MySQL table is called "Restaurant" - well, actually this side isn't that much important yet. (Which means I'll come back to that later.)
The PHP script is
<?php
mysql_connect("localhost","root","");
mysql_select_db("Restaurant");
$myQuery = "SELECT LibPlat FROM Plats";
$rs = mysql_query($myQuery);
while ($row = mysql_fetch_array($rs)) {
echo ($row['LibPlats']."<br />\n");
}
?>
My setup consists of Eclipse with PDT and Zend Debugger (latest version, i.e. 3.5.1 and just updated). I use Zend Server CE with its MySQL install (phpMyAdmin).
Basically the script does just what I've been asking it to do, except that the French accents (like in thé or café) don't appear (there's this rectangle instead).
Shawn Olson (or rather Andrew Penry on Olson's website) says that storing data in UTF-8 is not enough on MySQL: "[y]ou must also tell MySQL that the data you are passing into it is UTF-8 otherwise it will assume it is in its default encoding."
His code looks like this:
<?php
$DB = new mysqli('localhost', 'user', 'root', 'dbname');
$DB->query("SET NAMES 'utf8'");
if (!empty($_POST['ta'])) {
$DB->query("UPDATE document SET unicodeText='{$_POST['ta']}' WHERE ID=1");
}
$result = $DB->query("SELECT unicodeText FROM document WHERE ID=1");
$return = $result->fetch_object();
$result->close();
?>
I just have a little bit of a problem decyphering his code. I'm pretty sure that I can ignore his mysqli line. And $DB->query(""); looks pretty much the same way like my two-liner $myQuery = ""; mysql_query($myQuery); but then I run into some code I can't my hands nor tails of.
Does anyone know how to adapt Andrew's code snippet for my exercise? Or does anyone have a better idea of how to achieve that goal, and, as Andrew wrote, configuring the server may not always be an option, yet he hints that his code should eventually do the same thing as if I would set the server up to use unicode as the default character encoding.
Thank you!