0

So, when I update stuff in my database it turns for example this: Š to this: u0160 it would be ok if it turned into this: \u0160 so it would display right but it doesn’t.

This is my connection file:

<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'pwd');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
mysqli_set_charset($db,"utf8");
mysqli_query("set names utf8");
?>

And this is the query:

mysqli_query($db, "UPDATE schools SET subjectData='$json' WHERE id='$schoolID'");
  • Value of $json: {"subject":"A","desc":"A\u017d"}
  • Value of db entry: {"subject":"A","desc":"Au017d"}
Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
Uranium Developers
  • 132
  • 1
  • 4
  • 11
  • 1
    shownplease your table charset declaration? and value of your `$json` variable? and the code where you try to output values from databasE? – Alex Feb 12 '15 at 23:44
  • Is this really in your db or just when you output it?Look here http://stackoverflow.com/questions/279170/utf-8-all-the-way-through – Mihai Feb 12 '15 at 23:46

2 Answers2

4

This has nothing to do with UTF-8 at all, you're only handling pure ASCII values. Your issue is that a backslash, a necessary part of the JSON encoding, is disappearing as you enter it into the database. The reason for that would be that you're not escaping your data correctly. A backslash has a special escaping meaning in SQL, if you want to insert a literal backslash into the database it requires escaping. With mysqli, you should be using prepared statements:

$stmt = $db->prepare('UPDATE schools SET subjectData = ? WHERE id = ?');
$stmt->bind_param('ss', $json, $schoolID);
$stmt->execute();

See How can I prevent SQL injection in PHP? and The Great Escapism (Or: What You Need To Know To Work With Text Within Text).

Community
  • 1
  • 1
deceze
  • 510,633
  • 85
  • 743
  • 889
1

So you showed the variable value, but you didn't show the code where you extract values from database.

And another note : your value is not really utf8, it is json encoded string:

{"subject":"A","desc":"A\u017d"}

As you see, the original string is not equal to value stored in database:

{"subject":"A","desc":"Au017d"}

Saving raw json in database is not very best practice. I would suggest to save just values not objects.

But if you need this, you should use this when you insert and/or update records:

mysqli_query($db, "UPDATE schools SET subjectData='".mysqli_escape_string($json)."' WHERE id='$schoolID'");  
Alex
  • 16,739
  • 1
  • 28
  • 51