I'm using MySQLi to retrieve information from the database. All of my pages are encoded with UTF-8 without BOM, i have 2 pages to deal with, but the main problem is that on the database the information is showed in a regular way - but when i retrieve it it goes like this:
����� ����� - ���?
on the phpMyAdmin panel - the columns are latin1_general_ci (i tried to make it utf8_general as well - same output!).
the "mysql.php":
<?php
header('Content-type: text/xhtml; charset=windows-1255');
$mysql = new mysqli('localhost', 'elenbyin_vadim', 'pass33323', 'elenbyin_vadim');
?>
the "index.php", main parts:
<?php
include ('mysql.php');
include('functions.php');
if($_GET["lang"] == 'rus')
$lang = 'rus';
else if($_GET["lang"] == 'heb')
$lang = 'heb';
else
$lang = 'heb';
......
<div class="main_text">
<?
$result = $mysql->query('SELECT * FROM homepage');
while($row = mysqli_fetch_array($result)){
echo "".$row['title']."<br />".$row['text_heb']."";
}
?>
</div>
can someone help my to solve this problem?
You'll have to change the charset for it to work:
<?php
$mysql->set_charset('utf8');
$result = $mysql->query('SELECT * FROM homepage');
...
?>
#Class's comment - If you need it in all your pages you can add it to mysql.php:
<?php
header('Content-type: text/xhtml; charset=windows-1255');
$mysql = new mysqli('localhost', 'elenbyin_vadim', 'pass33323', 'elenbyin_vadim');
$mysql->set_charset('utf8');
?>
Also, make sure you set your collation to utf8_general_ci.
An older method will be to set the names to utf8:
<?php
$mysql->query("SET NAMES 'utf8'");
$result = $mysql->query('SELECT * FROM homepage');
...
?>
However according to set_charset() docs the first is preferrable:
Note: This is the preferred way to change the charset. Using
mysqli_query() to set it (such as SET NAMES utf8) is not recommended.
See the MySQL character set concepts section for more information.
Related
I have a problem, when I try to echo a cyrillic character, it return like ????
Here's 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?
Collation : 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();
}
?>
Worked after <? $conn->set_charset("utf8");?>
Add before your $sql
$conn->query('SET NAMES utf8');
You can read more about it here
Also you will need to set proper header for browser. You can do it by serveral ways for example in meta html tag or using header('Content-Type: text/html; charset=utf-8');
You should set collation per connection:
mysqli_set_charset
Also you can perform sql
SET NAMES utf8;
but it's 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();
I am assuming you are using Bulgarian and UTF8, same will work for Russian and other languages, just change "bg" to proper string.
I do not recommend you to use cp1251, because it breaks unexpectedly with apache mod_rewrite and other tools like this.
You need to do following checks:
Check if your database / table collation is some UTF8. It could be utf8_general_ci or Bulgarian - difference is minimal and is more sorting related. (utf8_general_ci is perfectly OK)
Check you have following statement executed right after connect - set names UTF8;. You can do $mysqli->query("set names utf8");
Make sure you have proper "tags". Here 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" on the html, but it works pretty well without it. I usually work without "BOM", and when I want to be 100% complaint, I create an include file bom.php that contain just the BOM symbol and include it prior HTML template in normal PHP way, e.g. include "bom.php".
Hope this helps, if not, please comment.
EDIT:
Someone suggested you must be sure if your data is properly stored in MySQL. Easiest way is to open PHP MySQL Admin. If Cyrillic is shown there, all is OK.
I think the issue is a step back, try to first encode the cyrillic characters correctly: How to encode cyrillic in mysql?
I'm a bit newbi in PHP. I implemented http://www.sanwebe.com/2013/03/loading-more-results-from-database solution in my new website: http://do2go.pl/do2go-nowa/
its working well - except encoding. My DB and all things are in UTF8. When fetch taking data from DB UTF8 seems not working.
Heres configuration and fetch code:
Config:
<?php
$db_username = 'kamio2_do2gonowa';
$db_password = 'JeremiasZ1!';
$db_name = 'kamio2_do2gonowa';
$db_host = 'localhost';
$item_per_page = 2;
mysqli_query ("SET NAMES 'utf8'"); mysqli_set_charset('utf8');
$connecDB = mysqli_connect($db_host, $db_username, $db_password,$db_name) or die('could not connect to database');
?>
And fetch:
<?php
include("config.inc.php"); //include config file
//sanitize post value
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
header('Content-Type: text/html; charset=UTF-8');
//throw HTTP error if page number is not valid
if(!is_numeric($page_number)){
header('HTTP/1.1 500 Invalid page number!');
exit();
}
//get current starting point of records
$position = ($page_number * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($connecDB, "SELECT id,introtext FROM w7wst_content ORDER BY id DESC LIMIT $position, $item_per_page");
//output results from database
echo '<ul class="page_result">';
while($row = mysqli_fetch_array($results))
{
echo '<li id="item_'.$row["id"].'"><span class="page_message">'.$row["introtext"].'</span></li>';
}
echo '</ul>';
?>
I added mysql_query ("SET NAMES 'utf8'"); mysql_set_charset('utf8'); but this does nothing. Still getting � symbols and ? instead of " All next 3 was changed directly in DB tables for html symbols which isn't a solution.
Any help appreciated! :)
(To close the question, since this was the solution to the OP's problem)
Add $connecDB->set_charset("utf8"); just before $results = mysqli_query($connecDB...
You are using mysql and mysqli in one script. Only use mysqli as mysql has been deprecated. That said try this:
mysqli_character_set_name($connectDB);
mysqli_set_char_set($connectDB, 'UTF8');
Set these after your connection script.
Did you check if they are properly stored in the table? Try typing this in your database(not in PHP):
SELECT * FROM w7wst_content;
and see if it's displaying properly. Alternatively you can check table contents with some tool like phpmyadmin. If it's not you have to set collation to something like utf8_general_ci.
EDIT: Also, how about setting the charset AFTER connecting to the database, hm? :)
core.php
$con=mysqli_connect("localhost","root","","mmogezgini");
header('Content-Type: text/html; charset=utf-8');
gamelisti.php
$result = mysqli_query($con,"SELECT * FROM games");
while($row = mysqli_fetch_array($result))
{
?>
HTML CODES
<?php echo $row['game_name']; ?>
HTML CODES
<?php }
mysqli_close($con);
?>
i use turkish characters like "ö,ç,ğ,ı" i see these correctly in database but when i select them from database and show with php echo they looks like question mark=(?)
my encoding on database utf8_general_ci
Double check your HTML encoding.
http://php.net/manual/en/mysqli.set-charset.php (just after you connect to DB: mysqli_set_charset($con, 'utf8');
Are you using prepared statements? (not related but important).
i have the mysql connection below:
$dbLink = mysql_connect('127.0.0.1', 'root', '');
mysql_set_charset('utf8', $dbLink);
mysql_select_db('test', $dbLink);
mysql_set_charset('utf-8');
it was working fine 1 week ago, but suddenly it is not showing the utf-8 or arabic or unicode contents which are stored in the database. but now even in the database the characters has been changed like سید اØمد Ø´Ûید Ú©ÛŒ صØÛŒØ and showing in the php the same. before everything was perfect. and the content was showing properly.
even now when i make a new entry in the database its showing fine but something went wrong with the old entries any help please.......
i have tried set names, mysql_set_charset & <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> but nothing happened. please help otherwise my site will be hanged up......
Use MYSQLi because MYSQL is now deprecated.
To set charset utf-8 use mysqli_set_charset() like this:
$dbLink = mysqli_connect('127.0.0.1', 'root', '');
mysqli_set_charset($dbLink , 'utf8');
mysqli_select_db($dbLink, 'test');
If for any reason it is still displaying wrong characters, add this to the beginning of your documents:
// Tell PHP that we're using UTF-8 strings until the end of the script
mb_internal_encoding('UTF-8');
// Tell PHP that we'll be outputting UTF-8 to the browser
mb_http_output('UTF-8');
UPDATE
Select some contents from your database and output the value using iconv() and see if it shows the wright charset:
<?php
$dbLink = mysqli_connect('127.0.0.1', 'root', '');
mysqli_set_charset($dbLink , 'utf8');
mysqli_select_db($dbLink, 'test');
function get_table_contents(){
global $dbLink;
$contents = array();
$query = "SELECT * FROM ||YOUR TABLE HERE||";
$result = mysqli_query($connection, $query);
while($content = mysqli_fetch_assoc($result)){
$contents[] = $content;
}
return $contents;
}
$data = get_table_contents();
?>
<html>
<head></head>
<body>
<?php echo iconv(mb_detect_encoding($data[0]['||YOUR COLUMN||'], "UTF-8,ISO-8859-1"), "UTF-8", $data[0]['||YOUR COLUMN||']); ?>
</body>
</html>
I am learning PHP programming, so I have setup testing database and try to do various things with it. So situation is like that:
Database collation is utf8_general_ci.
There is table "books" created by query
create table books
( isbn char(13) not null primary key,
author char(50),
title char(100),
price float(4,2)
);
Then it is filled with some sample data - note that text entries are in russian. This query is saved as utf-8 without BOM .sql and executed.
insert into books values
("5-8459-0046-8", "Майкл Морган", "Java 2. Руководство разработчика", 34.99),
("5-8459-1082-X", "Кристофер Негус", "Linux. Библия пользователя", 24.99),
("5-8459-1134-6", "Марина Смолина", "CorelDRAW X3. Самоучитель", 24.99),
("5-8459-0426-9", "Родерик Смит", "Сетевые средства Linux", 49.99);
When I review contents of created table via phpMyAdmin, I get correct results.
When I retrieve data from this table and try to display it via php, I get question marks instead of russian symbols. Here is piece of my php code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Books</title>
</head>
<body>
<?php
header("Content-type: text/html; charset=utf-8");
mysqli_set_charset('utf8');
# $db = new mysqli('localhost', 'login', 'password', 'database');
$query = "select * from books where ".$searchtype." like '%".$searchterm."%'";
$result = $db->query($query);
$num_results = $result->num_rows;
for ($i = 0; $i < $num_results; $i++) {
$row = $result->fetch_assoc();
echo "<p><strong>".($i+1).". Title: ";
echo htmlspecialchars (stripslashes($row['title']));
echo "</strong><br />Author: ";
echo stripslashes($row['author']);
echo "<br />ISBN: ";
echo stripslashes($row['isbn']);
echo "<br />Price: ";
echo stripslashes($row['price']);
echo "</p>";
}
...
And here is the output:
1. Название: Java 2. ??????????? ????????????
Автор: ????? ??????
ISBN: 5-8459-0046-8
Цена: 34.99
Can someone point out what I am doing wrong?
Can someone point out what I am doing wrong?
Yes, I can.
You didn't tell Mysql server, what data encoding you want.
Mysql can supply any encoding in case your page encoding is different from stored data encoding. And recode it on the fly.
Thus, it needs to be told of client's preferred encoding (your PHP code being that database client).
By default it's latin1. Thus, because there is no such symbols in the latin1 character table, question marks being returned instead.
There are 2 ways to tell mysql what encoding we want:
a slightly more preferred one is mysqli_set_charset() function (method in your case).
less preferred one is SET NAMES query.
But as long as you are using mysqli extension properly, doesn't really matter. (though you aren't)
Note that in mysql this encoding is called utf8, without dashes or spaces.
Try to set output charset:
SET NAMES 'utf-8'
SET CHARACTER SET utf-8
Create .htaccess file:
AddDefaultCharset utf-8
AddCharset utf-8 *
CharsetSourceEnc utf-8
CharsetDefault utf-8
Save files in UTF-8 without BOM.
Set charset in html head.
After your mysql_connect, set your connection to UTF-8 :
mysql_query("SET NAMES utf8");
Follow Alexander advices for .htaccess, header and files encoding
You probably need to call mysqli_set_charset('utf8'); after you set up your connection with new mysqli(...) as it works on a link rather than a global setting.
so..
# $db = new mysqli('localhost', 'login', 'password', 'database');
mysqli_set_charset($db, 'utf8');
$query = "select * from books where ".$searchtype." like '%".$searchterm."%'";
By the way, that query seems to be open to SQL-injection unless $searchterm is sanitized. Just something to keep in mind, consider using prepared statements.
And using # to suppress errors is generally not recommended, especially not during development. Better to deal with error-conditions.
after your mysql_query add
#mysql_query("SET character_set_server='utf8'; ");
#mysql_query("SET character_set_client='utf8'; ");
#mysql_query("SET character_set_results='utf8'; ");
#mysql_query("SET character_set_connection='utf8'; ");
#mysql_query("SET character_set_database='utf8'; ");
#mysql_query("SET collation_connection='utf8_general_ci'; ");
#mysql_query("SET collation_database='utf8_general_ci'; ");
#mysql_query("SET collation_server='utf8_general_ci'; ");
Try to put also in the HTML document Head the meta tag:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
this is different to the HTTP header header("Content-type: text/html; charset=utf-8");