Reputation: 1039
I am trying to create some pages using PHP / MySQL.
My database table is set to utf8_general_ci
and so are the table columns. If I use phpmyadmin and manually insert a page I can type all the € I want and they will be inserted as €. I can display this perfectly too.
However when I am trying to insert a page using mysqli the € will be converted to €
I am not doing any conversions of any kind. If I echo the page column fiels just before I am about to insert the page it still displays the € correctly.
The code:
$connection = new mysqli('localhost', 'root', '', 'some_db');
$query = 'INSERT INTO page (ID, title, content) VALUES (?, ?, ?)';
$params = array('iss', 'NULL', 'test title', '€ some content');
$stmt = $connection->prepare($query);
call_user_func_array(array($stmt, 'bind_param'), by_ref($params));
$stmt->execute();
The by_ref
function only makes a reference, nothing else. All works fine except it gives me a headache when it doesn't insert € correctly. Maybe it is not the bind_param, but something else. I would however like to know the answer!
Update:
Thanks to Digital Precision I figured out I would have to make sure the connection was going to use 'utf8'. However I only need to set it when using INSERT or UPDATE as SELECT did give me results back in utf8. Hope this helps someone
Upvotes: 1
Views: 1366
Reputation: 19999
PHPMyAdmin may be explicitly setting the connection charset to UTF-8 which is why it may work through the admin interface and not through your script. Check out mysqli::set_charset for more detailed info.
$connection->set_charset('utf8');
Edit
Try taking out the call_user_function:
$connection = new mysqli('localhost', 'root', '', 'some_db');
$query = 'INSERT INTO page (ID, title, content) VALUES (?, ?, ?)';
//$params = array('iss', 'NULL', 'test title', '€ some content');
$stmt = $connection->prepare($query);
// Replace this
//call_user_func_array(array($stmt, 'bind_param'), by_ref($params));
// With this
$stmt->bind_param('iss', 'NULL', 'test title', '€ some content');
$stmt->execute();
Upvotes: 3