Php mysql return?
I have a problem, when I try to repeat a Cyrillic character, it returns, for example
Here's the code
<?
include('db.php');
$sql = "SELECT * FROM menu_items WHERE reference=1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$rows = array();
while($row = $result->fetch_object()) {
$rows[] = json_encode($row);
}
$items = implode(',',$rows);
echo '['.$items.']';
}else {
echo "ERROR";
}
?>
Any idea?
Sort: utf8_general_ci
And db.php:
<?
$servername = "localhost";
$username = "test";
$password = "Conqwe333!";
$conn=mysqli_connect($servername,$username,$password,"test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Works after <? $conn->set_charset("utf8");?>
source to share
You must set up a mapping for each connection:
Also you can execute sql
SET NAMES utf8;
but not recommended
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $mysqli->error);
} else {
printf("Current character set: %s\n", $mysqli->character_set_name());
}
$mysqli->close();
source to share
I assume you are using Bulgarian and UTF8, the same will work in Russian and other languages, just change "bg" to the correct string.
I don't recommend using cp1251 because it breaks unexpectedly with apache mod_rewrite and other tools like this.
You need to perform the following checks:
- Check if your database / table collation is some UTF8. It can be utf8_general_ci or bulgarian - the difference is minimal and more related to sorting. (utf8_general_ci works great)
- You have the following instruction executed immediately after connecting -
set names UTF8;
. You can do$mysqli->query("set names utf8");
- Make sure you have the correct "tags". Here's an example:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang='bg' xml:lang='bg' xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> :)</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf8">
- You can include UTF8 "BOM" in the html, but it works pretty well without it. I usually work without a "BOM" and when I want to complain 100%, I create an include file
bom.php
that only contains the BOM character and includes it in front of the HTML template in normal PHP way, for example.include "bom.php"
...
Hope this helps, if not please comment.
EDIT:
Someone suggested that you make sure your data is stored correctly in MySQL. The easiest way is to open PHP MySQL Admin. If the Cyrillic alphabet is displayed there, everything is in order.
source to share
I think the problem is a step back, try to encode the cyrillic characters correctly first: How to encode cyrillic in mysql?
source to share