All foreign characters such as umlauts (ü) get deleted when trying to put them into mysql.
In debugging this problem I've went over the following:
My database is UTF-8
The table in question is InnoDB utf8_general_ci. Row is longtext utf8_general_ci
I've added mysqli_set_charset($mysqli, "utf8"); right after $mysqli = new mysqli($hostname, $username, $password, $database);
It goes in using the following php:
$stmt = $mysqli->prepare("
UPDATE post
SET post = ?,
title = ?
WHERE id = ?
");
$stmt->bind_param("ssi", $clean_html, $titlePost, $id);
String before going being updated in db is
<p>SOME NEW TEXT</p><p> </p><p>üü</p>
But still nothing. The umlauts disappear. In the DB it shows up as
<p>SOME NEW TEXT</p><p></p><p></p>
What other debugging steps should I take? Thank you
Try utf8_encode() and utf8_decode() maybe it can help. before setting the value to database try
$value = utf8_encode($value);
Related
I have a database that contains latin chars like á, é, ç etc. I can insert tuples with those chars using the MySQL admin interface by writing the SQL insert statements there. I can also read and display them without any problem. But I can't insert new data properly using PHP.
$mysqli = new mysqli("localhost", "root", "", "budgets");
$data = mysqli_real_escape_string($mysqli, "bananá");
$stmt = $mysqli->prepare("INSERT INTO items(id_budget, description, unit_price, quantity) VALUES (1, ?, 3, 3);");
$stmt->bind_param("s", $data);
$stmt->execute();
I have read several threads suggesting to use mysqli_real_escape_string(), and making sure the charsets were configured properly, but nothing worked.
I tried using different charsets in the database but the á is always replaced by strange symbols. Currently I'm using utf8_general_ci as the charset of the database.
Thank you in advance for any assistance.
First thing setup your table rows collcation to utf8_unicode_c
And add $mysqli->set_charset("utf8"); to your connection code
Finaly your code should look like this :
$mysqli = mysqli_connect(HOST_NAME,DB_USER,DB_PASS,DB_NAME);
if($mysqli === false) {
die("Something was wrong ! Please try again later."); // Error if connection not ok.
}
$mysqli->set_charset("utf8");
$data = "bananá";
$stmt = $mysqli->prepare("INSERT INTO items(id_budget, description, unit_price, quantity) VALUES (1, ?, 3, 3);");
$stmt->bind_param("s", $data);
$stmt->execute();
$stmt->close();
$mysqli->close();
I'm inserting utf-8 data to the database with this code
$conn = new mysqli($hostname, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_set_charset($conn,"utf8");
$sql = "INSERT INTO Movies (Name, Year)
VALUES ('".$_POST["name"]."', '".$_POST["year"]."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
But the data is added like this:
What should I do?
This is something I think you must fix in the back end, the PHP code is perfect, but you need to configure your database to utf-8 as well. You appear to be using PHPmyAdmin, when you create or import the table, you should see a drop down box to select the file's character set. Change this and you should be good to go!
That should start (end?) with Arabic 'noon' (ن), correct?
ن is the "html entity" for 'noon'.
Was the user filling in an html <form>? does it include a charset, such as <form accept-charset="UTF-8">? If not, that might be the solution.
Is the column/table declared CHARACTER SET utf8 (or utf8mb4, but not utf32)? It needs to be. See SHOW CREATE TABLE.
You can use alter command in mysql to change all the fields to utf8 format,
Please check the sql query
ALTER TABLE `Movies` CHANGE `Name` `Name` VARCHAR(40) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL;
This question already has answers here:
The ultimate emoji encoding scheme
(2 answers)
Closed 6 years ago.
I am having problems decoding UTF8 characters in my script from my sql.
Lets say I have two characters coming from mysql:
'á' & ❤️
with my script á is decoded fine however, the emoticon is decoded in â¤ï
What am I doing wrong?
$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT * FROM `community` ORDER BY `community`.`date` DESC LIMIT 25";
mysqli_set_charset($conn, "utf8"); //UTF8
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$comment = $row['comment'];
echo $comment . "</br>";
//echo htmlentities($comment); not working... white screen
}
UPDATE
I have changed Database and Tables
$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT * FROM `community` ORDER BY `community`.`date` DESC LIMIT 25";
mysqli_set_charset($conn, "utf8"); //UTF8
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$comment = $row['comment'];
$comment = mb_convert_encoding($comment, "UTF-8");
echo $comment . "</br>";
//echo htmlentities($comment); not working... white screen
}
Your issue here is probably with the database.
You need to set your database charset to UTF-8 in order to query it correctly, what you are doing is to get a string and setting Client side default charset using
mysqli_set_charset($conn, "utf8"); //UTF8
That's not enough, so I would recommend you to run an SQL query like
ALTER DATABASE databasename CHARACTER SET utf8 COLLATE utf8_unicode_ci;
in order to update it. If what you need is to change a single table use
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
Finally you can check it using
SELECT DEFAULT_COLLATION_NAME FROM data_dictionary.SCHEMAS WHERE SCHEMA_NAME = 'databasename' LIMIT 1;
As an extra appointment and just in case in PHP you can convert the encoding of a string using
$comment = mb_convert_encoding($comment, "UTF-8"); //Change encoding
echo mb_detect_encoding($str, "auto"); // Check encoding
Of course you should make a backup before making any of these changes, just in case.
EDIT: The proper order to run these queries, is:
Run it in the whole DB using the first query
Run it table by table using the second query
Check if the charset has been set correctly using the third query
EDIT 2 : Remember to set the tag <meta charset="UTF-8"> in your html file.
I hope this helps you :)
I am trying to INSERT an row to MySQL database like this :
function insertUserRating($username, $eventid, $ratingval, $ratingtext) {
mysqli_query($this -> db -> connect(), "SET NAMES 'utf8';");
$datetime = date("Y-m-d H:i:s");
$query = mysqli_query($this -> db -> connect(), " INSERT INTO `rating` ( `id_user` ,`id_event` ,`rating_value` ,`rating_text` ,`rating_date`)
VALUES ((SELECT id_user FROM user WHERE username= '$username' ), '$eventid', '$ratingval', '$ratingtext', '$datetime' )");
if ($query) {
return true;
} else {
return false;
}
}
the connect function is like this :
public function connect() {
require_once 'config.php';
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
$con -> set_charset("utf8");
if (mysqli_connect_errno()) {
throw new Exception(mysqli_connect_error(), mysqli_connect_errno());}
return $con;
}
But still if I try to insert row with $ratingtext having some unicode characters for example : Lepšišie I only get Lepieie in the table. Table has utf8_slovak_ci coding.
The php module in mysql can't set itself to utf8 automatically based on the configurations. Probably nobody knows, why. The workaround is a
SET NAMES 'utf8';
query at the beginning of every mysql connection.
I see in your question, that you are playing around with this bug already. No, you don't need utf8_encode and such tricks after you set this up.
Alternative things ($something->connect and like) won't work, they all are based on the mysql module of the php, which is a module of the apache. It is an old bug, which probably won't be ever repaired. Good luck!
I need to use bind_param to get away with data injection. When I use bind_param, special characters such as € or ب are being saved in mysql as صذق.
1-I am sure mysql table is set up correctly.
2-I have changed the word processor's encoding to UTF8.
3-I have included many utf8 character sets all over the place.
Any thoughts how to fix this? or maybe I should start using other methods such as mysqli_real_escape_string?
($_POST["post_word"] is generated in a separate page)
$connect = mysqli_connect("r"," r","r","r"); //not real data here
$connect->set_charset('utf8');
$connect->query("SET NAMES utf8");
$querye= mysql_query("SET NAMES utf8");
mysqli_query($connect,"INSERT INTO wordtable ( wdate) VALUES (CURRENT_TIMESTAMP())");
$sqlz = "SELECT wid FROM wordtable ORDER BY wdate DESC LIMIT 1";
$resultz = mysql_query($sqlz);
$rowz = mysql_fetch_array($resultz);
$wid=$rowz['wid'];
$mysqli = new mysqli(HOSTNAME, MYSQLUSER, MYSQLPASS, MYSQLDB);
$connect->set_charset('utf8');
$unsafe_variable = $_POST["post_word"];
$stmt = $mysqli->prepare("UPDATE wordtable SET word=(?)
WHERE wid='$wid' ");
$stmt->bind_param("s", $unsafe_variable);
$stmt->execute();
$stmt->close();
$mysqli->close();
Would it be perhaps
$querye= mysql_query("SET NAMES utf8");
Your querying with MySQL here