MySql UTF8 collation data with accents not displayed properly when PHP fetched - php

I am fetching some data having UTF8 collation (utf8_unicode_ci) from a MySQL database with PHP. I am using this piece of code:
function advancedDatabaseSearch($pattern, $lpref) {
$link = mysql_connect(DB_URL, DB_USER, DB_PWD);
if (!$link) {
return 'Could not connect: ' . mysql_error();
}
$esc_value = mysql_real_escape_string($pattern);
$esc_lpref = mysql_real_escape_string($lpref);
mysql_select_db(DB_NAME, $link);
$query = "SELECT RAWVALUE FROM rawvalueitem "
."WHERE RAWVALUE LIKE '".$esc_value."' "
."AND LANGUAGE = '".$esc_lpref."' "
."ORDER BY RAWVALUE ASC";
$result = mysql_query($query);
$return = "";
while($row = mysql_fetch_array($result)) {
$return = $return.$row['RAWVALUE']." ";
}
mysql_close($link);
return $return;
}
and then from the php called by Ajax:
$result = advancedDatabaseSearch($tttmp, $lpref);
echo $result;
return;
Yet, when I display the result in a text area, the accents are not displayed properly:
On the other side, when I fetch UT8 data from a file:
if ( $file_loc != NULL ) {
if ( file_exists($file_loc) ) {
$handle = fopen($file_loc, "rb");
$contents = fread($handle, filesize($file_loc));
fclose($handle);
$result = $contents;
}
}
echo $result;
return;
I don't get this issue !!! How can I solve it when using PHP to fetch data from MySql?

Did you set UTF-8 as the default character set of your database connection?
mysql_set_charset('utf8', $link);
http://www.php.net/manual/en/function.mysql-set-charset.php
Also, does your page have a <meta> tag with the correct character set?

This is working like a.. you now!
<?php
$config_db_server='localhost';
$config_db_server_username='root';
$config_db_server_password='';
$config_db_database='test';
$config_db_charset='utf8';
$config_db_collation='utf8_general_ci';
$config_table_prefix='class_';
$config_live_site='http://localhost';
$config_abs_path='C:\xampp\htdocs';
$config_debug=0;
$dbLink = mysql_connect($config_db_server, $config_db_server_username, $config_db_server_password);
mysql_query("SET character_set_results=utf8", $dbLink);
mb_internal_encoding('utf8');
mysql_query("set names 'utf8'",$dbLink);
?>
Change here your db connect: ( $dbLink = mysql_connect($config_db_server, $config_db_server_username, $config_db_server_password); )

Related

PHP UTF-8 Encoding is messing up

I'm outputting some multi-lingual data from my database into a JSON object, but the output isn't showing foreign characters, it just shows question marks even though I have the header charset set to utf8 as such:
header('Content-Type: application/json; charset=utf-8');
When I look at the data in phpMyAdmin, it shows the characters correctly. Is there something I'm doing wrong?
Here is the PHP code that is formatting the JSON output:
$numRows = new stdClass();
$mysqli = dbiConnect();
$query = "SELECT * FROM country_codes";
if ($stmt = $mysqli->prepare($query)) {
/* execute query */
$stmt->execute();
/* store result */
$stmt->store_result();
$numRows->cc = $stmt->num_rows;
/* close statement */
$stmt->close();
}
$mysqli->close();
$count = 0;
$dataCountryCodes = '{';
$mysqli = dbiConnect();
$query = "SELECT * FROM country_codes";
if ($result = $mysqli->query($query)) {
while($row = $result->fetch_assoc()){
$count++;
$rowData = new stdClass();
$rowData->code = $row['code'];
$rowData->name = $row['name'];
$dataCountryCodes = $dataCountryCodes.'"'.$rowData->code.'": {"Code":"'.$rowData->code.'","Country":"'.$rowData->name.'"}';
if ($count != $numRows->cc) {
$dataCountryCodes = $dataCountryCodes.',';
}
}
}
$mysqli->close();
$dataCountryCodes = $dataCountryCodes.'}';
if ($returnCountryCodes == 1) {
return $dataCountryCodes;
} else {
header('Content-Type: application/json; charset=utf-8');
echo ($dataCountryCodes);
}
This is what I am getting:
{"AE": {"Code":"AE","Country":"United Arab Emirates (???????? ???????? ????????)"}}
This is what I got when it was hand coded, this would render fine after I translated the JSON to HTML:
{"AE": {"Code":"AE","Country":"United Arab Emirates (الإمارات العربيّة المتّحدة)"}}
You didn't show dbiConnect function. Check it and try using SET NAMES 'UTF8' after connecting to MySQL:
$con=mysqli_connect("host", "user", "pw", "db");
if (!$con)
{
die('Failed to connect to mySQL: ' .mysqli_connect_errno());
}
/* change character set to utf8 */
if (!$con->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $con->error);
}
As the manual says:
SET NAMES indicates what character set the client will use to send SQL
statements to the server... It also specifies the character set that the server should
use for sending results back to the client.
try this:
$mysqli = dbiConnect();
$mysqli->query("set names utf8")

replace non breaking space PHP

* The json_encode is returning NULL? is NOT the answer. I still receive a NULL when using the json_encode.*
I am very new to PHP, so if you could edit the section with the fixed code, I'd appreciate it.
This is my problem:
When an article under "introtext" contains non breaking lines, it returns NULL. The articles that do not have a non breaking space show up just fine.
This is my question:
How can I get the articles under "introtext" to display properly even if they contain a non breaking space.
Here's the code:
$connection = mysqli_connect($host, $user, $pass);
//Check to see if we can connect to the server
if(!$connection)
{
die("Database server connection failed.");
}else{
//Attempt to select the database
$dbconnect = mysqli_select_db($connection, $db);
//Check to see if we could select the database
if(!$dbconnect)
{
die("Unable to connect to the specified database!");
}else{
$catID = $_GET['catid'];
$id = $_GET['id'];
$rtn = $_GET['rtn'];
if($id!=""){
$query = "SELECT * FROM tcp_content WHERE id=" . $id . "";
}else{
$query = "SELECT * FROM tcp_content WHERE catid=" . $catID . " ORDER BY publish_up DESC LIMIT " . $rtn . "";
}
$resultset = mysqli_query($connection,$query);
$records = array();
//Loop through all records and add them to array
while($r = mysqli_fetch_assoc($resultset))
{
$r['introtext'] = print_r($r['introtext'],true);
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
?>
here are two links:
This link contains the non breaking space, so you'll notice introtext returns NULL
This link does NOT contain the non breaking space, so you'll notice the article shows
I found this link json_encode problem
see second answer. Charles is suggesting that use iconv() to remove URL encoded non-breaking space.
I finally figured it out and got it working
$r['introtext'] = utf8_encode($r['introtext']);
$r['introtext'] = str_replace(chr(194).chr(160),' ',$r['introtext']);
$r['introtext'] = str_replace(chr(194).chr(147),'"',$r['introtext']);
$r['introtext'] = str_replace(chr(194).chr(148),'"',$r['introtext']);
$r['introtext'] = str_replace(chr(194).chr(146),"'",$r['introtext']);
$r['introtext'] = str_replace(chr(194).chr(145),"'",$r['introtext']);
$r['introtext'] = htmlentities($r['introtext'], ENT_QUOTES | ENT_IGNORE, "UTF-8");
$records = $r;

PHP XML parsing issue

I want to be able to parse a SQL database with PHP to output an XML, however I cannot get it to show the table name and all of it's contents. I could use some help, here is my code without login information:
I have defined the db server,mdb user and pass, and db name; should anything else be defined?
<?php
// connection to the database
$dbhandle = mysql_connect(DB_SERVER, DB_USER, DB_PASS)
or die("Unable to connect to MySQL");
// select a database to work with
$selected = mysql_select_db(DB_NAME, $dbhandle)
or die("Could not select data");
// return all available tables
$result_tbl = mysql_query( "SHOW TABLES FROM "DB_NAME, $dbhandle );
$tables = array();
while ($row = mysql_fetch_row($result_tbl)) {
$tables[] = $row[0];
}
$output = "<?xml version=\"1.0\" ?>\n";
$output .= "<schema>";
// iterate over each table and return the fields for each table
foreach ( $tables as $table ) {
$output .= "<table name=\"$table\">";
$result_fld = mysql_query( "SHOW FIELDS FROM "$table, $dbhandle );
while( $row1 = mysql_fetch_row($result_fld) ) {
$output .= "<field name=\"$row1[0]\" type=\"$row1[1]\"";
$output .= ($row1[3] == "PRI") ? " primary_key=\"yes\" />" : " />";
}
$output .= "</table>";
}
$output .= "</schema>";
// tell the browser what kind of file is come in
header("Content-type: text/xml");
// print out XML that describes the schema
echo $output;
// close the connection
mysql_close($dbhandle);
?>
I think it's better to use standard php class XmlWriter for this one.
Look at http://www.php.net/manual/en/book.xmlwriter.php
$result_tbl = mysql_query( "SHOW TABLES FROM "DB_NAME, $dbhandle );
^^^---typo
$result_fld = mysql_query( "SHOW FIELDS FROM "$table, $dbhandle );
^^^---typo
You've got at least two typos in your queries. Most likely you want this:
$result_tbl = mysql_query("SHOW TABLES FROM " . DB_NAME, $dbhandle) or die(mysql_error());
and
$result_fld = mysql_query("SHOW FIELDS FROM $table", $dbhandle) or die(mysql_error());
Note the concatenation operator (.) on the first one, and the addition of or die(...). Never assume a query succeeds. even if the query string itself is syntactically correct, there's far too many OTHER reasons is could fail to NOT check for an error condition.

How to get a list of databases?

I was wondering if there's a way in PHP to list all available databases by usage of mysqli. The following works smooth in MySQL (see php docs):
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$db_list = mysql_list_dbs($link);
while ($row = mysql_fetch_object($db_list)) {
echo $row->Database . "\n";
}
Can I Change:
$db_list = mysql_list_dbs($link); // mysql
Into something like:
$db_list = mysqli_list_dbs($link); // mysqli
If this is not working, would it be possible to convert a created mysqli connection into a regular mysql and continue fetching/querying on the new converted connection?
It doesn't appear as though there's a function available to do this, but you can execute a show databases; query and the rows returned will be the databases available.
EXAMPLE:
Replace this:
$db_list = mysql_list_dbs($link); //mysql
With this:
$db_list = mysqli_query($link, "SHOW DATABASES"); //mysqli
I realize this is an old thread but, searching the 'net still doesn't seem to help. Here's my solution;
$sql="SHOW DATABASES";
$link = mysqli_connect($dbhost,$dbuser,$dbpass) or die ('Error connecting to mysql: ' . mysqli_error($link).'\r\n');
if (!($result=mysqli_query($link,$sql))) {
printf("Error: %s\n", mysqli_error($link));
}
while( $row = mysqli_fetch_row( $result ) ){
if (($row[0]!="information_schema") && ($row[0]!="mysql")) {
echo $row[0]."\r\n";
}
}
Similar to Rick's answer, but this is the way to do it if you prefer to use mysqli in object-orientated fashion:
$mysqli = ... // This object is my equivalent of Rick's $link object.
$sql = "SHOW DATABASES";
$result = $mysqli->query($sql);
if ($result === false) {
throw new Exception("Could not execute query: " . $mysqli->error);
}
$db_names = array();
while($row = $result->fetch_array(MYSQLI_NUM)) { // for each row of the resultset
$db_names[] = $row[0]; // Add db name to $db_names array
}
echo "Database names: " . PHP_EOL . print_r($db_names, TRUE); // display array
Here is a complete and extended solution for the answer, there are some databases that you do not need to read because those databases are system databases and we do not want them to appear on our result set, these system databases differ by the setup you have in your SQL so this solution will help in any kind of situations.
first you have to make database connection in OOP
//error reporting Procedural way
//mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//error reporting OOP way
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL & MYSQLI_REPORT_STRICT;
$conn = new mysqli("localhost","root","kasun12345");
using Index array of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($row = $result->fetch_array(MYSQLI_NUM)){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if($row[0] == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'.$row[0];
}
}
same with Assoc array of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if($row["Database"] == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'.$row["Database"];
}
}
same using object of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($obj = $result->fetch_object()){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if( $obj->Database == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'. $obj->Database;
}
}

Return sql query as array

I'm using jqueryui and its Autocomplete plugin. It use a json to extract items.
I want to modify it so that items will be extracted from my db.
Here is how items should be :
$items = array(
"Great <em>Bittern</em>"=>"Botaurus stellaris",
"Great2 <em>Bittern</em>"=>"Botaurus stellaris 2"
);
How to make an sql query that extract data from a table and write it like the code above into the php file ?
Table : customer
id_customer | name_customer | country_customer
I want that array produce id_customer => name_customer
The query is just:
SELECT id_customer, name_customer FROM customer
and you can generate the array like so (assuming you are using MySQL):
$items = array();
$result = mysql_query($sql);
while(($row = mysql_fetch_assoc($result))) {
$items[$row['id_customer']] = $row['name_customer'];
}
References: MySQL SELECT syntax, mysql_query(), mysql_fetch_assoc()
<?php
//Use mysql_connect for connect to a Db
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// Select a DB
$db_selected = mysql_select_db('db_name', $link);
if (!$db_selected) {
die ('Can\'t use dbame_n : ' . mysql_error());
}
//Build a query
$sql = "SELECT id_customer, name_customer FROM customer";
//Send de query to db
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
// Initialize Array
$arr_customers = array();
while(($row = mysql_fetch_assoc($result))) {
$arr_customers[$row['id_customer']] = $row['name_customer'];
}
// convert to JSON
$json = json_encode($arr_customers);
// Send to JqueryUI
echo $json;
exit();
?>

Categories