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? :)
Related
honestly I am coming here after trying everything I could find online in order to fix that problem but nothing worked..
I have a phpmyadmin database table that encoded to utf_general_ci, when I insert data in Hebrew into it it works fine and I can see the Hebrew in the table on PhpMyAdmin, but when I need to retrieve the Hebrew data from the table that's when the problem starts...
right now I am using a simple sql query to select data from the table and I tried every code that should fix it I could find online but nothing seems to work.
my current code is:
<?php
$db = "android";
$username = "root";
$password = "";
$host = "localhost";
$sql = "select * from sample;";
$conn = mysqli_connect($host,$username,$password,$db);
$conn->set_charset('utf8');
$result = mysqli_query($conn,$sql);
$response = array();
while($row = mysqli_fetch_array($result))
{
array_push($response,array($row[0],$row[1]));
}
$str = json_encode(array($response));
echo $str;
mysqli_close($conn);
?>
and the output of the Hebrew word is \u05d4\u05d9\u05d9 what seems like a different encoding, my php file is encoded to UTF-8 and I am using npp to write it.
please try helping me out on this one cause I couldn't find an answer
This is a json_encode() behaviour, by default Unicode char are escaped as \u...
Try with JSON_UNESCAPED_UNICODE flag :
<?php
echo json_encode($arr, JSON_UNESCAPED_UNICODE);
I have a successful connection to the database through this php script but it is not returning any values even though it is connected. I am checking for the results on my web browser and it just returns a blank screen. I have used the same script (different queries) to access two other tables in the database and they are both working fine. Here is my code:
<?php
$username = "xx";
$password = "xxx";
$host = "xxxxx";
$database="xxxxx";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "SELECT `AUTHOR`, `In_order` from `authors`";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
It is probably some silly mistake that I have over looked but I have been stuck on it for longer than I should! thanks in advance for any feedback
Tried you code locally on some data and it returns everything ok.
I needed to change the select to match my data
So I am 95% sure the problem is in your query / db settings.
I would first check if your columns in database is really called AUTHOR and 'In_order' with the exact capital letters.
MySql names can be case sensitive depending on your db server settings, and this could be the problem
Sidenote: if you can research mysqli and pdo for connecting to DB instead of mysql that is deprecated.
Try this:
$myquery = "SELECT `AUTHOR`, `In_order` from `authors`";
$query = mysql_query($myquery);
$num = mysql_num_rows($query);
var_dump($query);
var_dump($num);
echo mysql_error();
and tell us what it all says.
Edit: okay, so it's 231 rows in your table, as the var_dump($num) says. Now let's try and get them at last, but in a slightly more efficient way:
while ($row = mysql_fetch_assoc($query)) {
$data[] = $row;
}
echo json_encode($data);
I have a feeling that your "for" loop and mysql_fetch_assoc() inside is what plays tricks with you, because both of them use different internal counters.
Hi I know this is a little general but its something I cant seem to work out by reading online.
Im trying to connnect to a database using php / mysqli using a wamp server and a database which is local host on php admin.
No matter what I try i keep getting the error Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given when i try to output the contents of the database.
the code im using is:
if (isset($_POST["submit"]))
{
$con = mysqli_connect("localhost");
if ($con == true)
{
echo "Database connection established";
}
else
{
die("Unable to connect to database");
}
$result = mysqli_query($con,"SELECT *");
while($row = mysqli_fetch_array($result))
{
echo $row['login'];
}
}
I will be good if you have a look at the standard mysqli_connect here
I will dont seem to see where you have selected any data base before attempting to dump it contents.
<?php
//set up basic connection :
$con = mysqli_connect("host","user","passw","db") or die("Error " . mysqli_error($con));
?>
Following this basic standard will also help you know where prob is.
you have to select from table . or mysqli dont know what table are you selecting from.
change this
$result = mysqli_query($con,"SELECT *");
to
$result = mysqli_query($con,"SELECT * FROM table_name ");
table_name is the name of your table
and your connection is tottally wrong.
use this
$con = mysqli_connect("hostname","username","password","database_name");
you have to learn here how to connect and use mysqli
I have a problem with polish characters. I can't get correctly written words, like '?ukasz' instead of "Łukasz" or even "null", when it supposed to be "Kraków". I tried "mysql_set_charset('utf-8'/'iso-8859-1')" after mysql_connect or iconv(on json_encode($output)) and it's still the same (except now there is "Krak\u00f3" instead of "null"). I'll appreciate any help.
This is a php file for my Android app:
$id_client = $_REQUEST['id_klienta'];
$con=mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db('courier_helper') or die(mysql_error());
$sql=mysql_query("SELECT * FROM `clients` WHERE id_klienta='$id_client'");
while($r=mysql_fetch_assoc($sql))
$output[]=$r;
print(json_encode($output));
mysql_close($con);
?>
You have to make sure, that you are using UTF-8 everywhere:
script file encoding (UTF-8 instead of ANSI) - you can set encoding it in Notepad++
html code (meta charset)
database table charset (when you are creating table or database)
database mysql_set_charset('utf8', $connection_obj);
database SET NAMES utf8 - run that SQL command after connecting
And one more thing - get familiar with PDO. This is my PDO connect function I use:
function DbConnect()
{
$db_host = "localhost";
$db_name = "database_name";
$db_user = "your_username";
$db_pass = "your_passwd";
$link = new PDO("mysql:host=$db_host;dbname=$db_name; charset=UTF-8", $db_user, $db_pass);
$link->exec("set names utf8;");
return $link;
}
You can use that function like this (this is PDO example):
$link = DbConnect();
$query = $link->prepare("SELECT id FROM wp_users");
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
You should have your database storing data as UTF8, which means converting your existing tables.
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
You also need to make sure your connection to the database is UTF8. You can make sure of that by running a SET NAMES query right after your connect.
SET NAMES UTF8
As others mentioned, you should start using PDO.
This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 12 months ago.
I have a mysql table with contents
the structure is here:
I want to read and print the content of this table to html
This is my code:
<?php
include("config.php");
$global_dbh = mysql_connect($hostname, $username, $password)
or die("Could not connect to database");
mysql_select_db($db)
or die("Could not select database");
function display_db_query($query_string, $connection, $header_bool, $table_params) {
// perform the database query
$result_id = mysql_query($query_string, $connection)
or die("display_db_query:" . mysql_error());
// find out the number of columns in result
$column_count = mysql_num_fields($result_id)
or die("display_db_query:" . mysql_error());
// Here the table attributes from the $table_params variable are added
print("<TABLE $table_params >\n");
// optionally print a bold header at top of table
if($header_bool) {
print("<TR>");
for($column_num = 0; $column_num < $column_count; $column_num++) {
$field_name = mysql_field_name($result_id, $column_num);
print("<TH>$field_name</TH>");
}
print("</TR>\n");
}
// print the body of the table
while($row = mysql_fetch_row($result_id)) {
print("<TR ALIGN=LEFT VALIGN=TOP>");
for($column_num = 0; $column_num < $column_count; $column_num++) {
print("<TD>$row[$column_num]</TD>\n");
}
print("</TR>\n");
}
print("</TABLE>\n");
}
function display_db_table($tablename, $connection, $header_bool, $table_params) {
$query_string = "SELECT * FROM $tablename";
display_db_query($query_string, $connection,
$header_bool, $table_params);
}
?>
<HTML><HEAD><TITLE>Displaying a MySQL table</TITLE></HEAD>
<BODY>
<TABLE><TR><TD>
<?php
//In this example the table name to be displayed is static, but it could be taken from a form
$table = "submits";
display_db_table($table, $global_dbh,
TRUE, "border='2'");
?>
</TD></TR></TABLE></BODY></HTML>
but I get ???????? as the results:
Where is my mistake?
Four good steps to always get correctly encoded UTF-8 text:
1) Run this query before any other query:
mysql_query("set names 'utf8'");
2) Add this to your HTML head:
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
3) Add this at top of your PHP code:
header("Content-Type: text/html;charset=UTF-8");
4) Save your file with UTF-8 without BOM encoding using Notepad++ or any other good text-editor / IDE.
Set the charset as utf8 as follows:
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
You are not defining your HTML page as UTF-8. See this question on ways to do that.
You may also need to set your database connection explicitly to UTF8. Doing a
mysql_query("SET NAMES utf8;");
^
Put it right under your database connection script or include and MAKE sure you have it placed before you do any necessary queries. Also, for collocation please take the time to make sure your
setting it for your proper syntax type and general_ci seems working good for me when used. As a finale, clear your cache after banging your head, set your browser to proper encoding toolbar->view->encoding
Setting the connection to UTF8 after establishing the connection takes care of the problem. Don't do this if the first step already works.
UTF-8 content from MySQL table with PDO
To correctly get latin characters and so on from a MySQL table with PDO,
there is an hidden info coming from a "User Contributed Note" in the PHP manual website
(the crazy thing is that originally, that contribution was downvoted, now luckily turned to positive .. sometime some people need to got blamed)
my credits credits go to this article that pulled the solution and probably made that "User Contributed Note" to turn positive
If you want to have a clean database connection with correct Unicode characters
$this->dbh = new PDO(
"mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=utf8",
DB_USER,
DB_PASS);
try this :
mysql_set_charset('utf8', $yourConnection);
Old ways have been deprecated. If you are using PHP > 5.0.5 and using mysqli the new syntax is now:
$connection->set_charset("utf8")
Where $connection is a reference to your connection to the DB.
I tried several solutions but the only one that worked
is that of Hari Dass:
$conn->set_charset("utf8");