Escaping single quotes and unicode symbols in php [duplicate] - php

This question already has answers here:
UTF-8 all the way through
(13 answers)
How to prevent XSS with HTML/PHP?
(9 answers)
Closed 3 years ago.
I am using php to develop a news app where the admin will feed in the news item with its descriptions and finally get displayed to users. I am using mysql database.
Everything seems to be working fine but I am not able to escape single quotes as well as display certain currency symbols in my output text. I am using UTF-8 charset. I have used str_replace function but to no avail. I have also tried htmlentities($mystring, ENT_QUOTES | ENT_IGNORE, ‘UTF-8) and this actually ignored (removed) the single quotes and symbols instead of escaping and displaying them as they are. I am also using UTF-8_general_ci in the table column of mysql.
This is my code for retrieving the data :
try{
$pdo = new PDO("mysql:host=$hostname;dbname=$dbname",
$username,$password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $pdo->prepare("SELECT * FROM feed WHERE news_id = ?");
$stmt->bindParam(1,$myval);
$stmt->execute();
while($myrow = $stmt->fetch()){
$newarray[] = $myrow;
}
$mystring = $newarray[0]['body'];
$mystring = str_replace("'","/'",$mystring);
echo $mystring;
} catch(PDOException $e){
echo 'Failed to retriev database item ' . $e->getMessage();
}
Below is an example output:
International Monetary Fund�s (IMF�s) Extended Credit Facility (ECF) programme, the raising of the $3-billion Eurobond at a lower coupon rate, and the positive Fitch rating of Ghana should be enough to demonstrate that, the economy is on track to impact the strength of the Ghana cedi. �In the last couple of weeks, the Bank of Ghana for instance, released a large chunk of dollars to players in the banking industry to meet our requirements. That was unprecedented and we feel that should the speculations stop, the Ghana cedi will stabilise the way we want it�,

Try to specify utf8 for PDO connection
$pdo = new PDO("mysql:host=$host;dbname=$db;charset=utf8", $username,$password);
If you still got the issue, try to run this query straight after the connection
$pdo->exec("set names utf8");
These steps should fix your issue but only if the data is correctly saved on your database, and you have the correct charset collation specified for your db, table and fields.

Related

Querying by a php a table containing emoji returns question marks [duplicate]

This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 3 years ago.
I am trying to retrieve a number of rows from a mysql DB, some of which containing emojis, through the following function:
<?php
ini_set('mssql.charset', 'UTF-8');
//$mysqli->query("SET NAMES 'utf8'");
$mysqli->query("SET character_set_client=utf8mb4");
$mysqli->query("SET character_set_connection=utf8mb4");
$mysqli->query("SET character_set_results=utf8mb4");
$mysqli->set_charset("utf8");
$sth = $mysqli->query($query);
if (!$sth) error_log("error Json query: $query");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
//var_dump($rows);
print json_encode($rows, JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE);
?>
Yet each emoji occurrence is substituted by a variable number of question marks, yet
if I conversely execute the query of the php script directly on Sequel Pro, the emojis show correctly. Apparently there is therefore some error in the function above, but I tried anything, as you may see, without success.
How should the query be configured instead?
I thank Paul for the hint, the issue was related to the redundant use of:
$mysqli->set_charset("utf8")
that apparently replaced the previous commands, taking it out the emojis showed just fine.

SQL query with accented characters [duplicate]

This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 4 years ago.
I migrated a project to a new host. So I transferred my files and my database. But since then, my sql queries with accented characters no longer work (NULL):
php file:
$ product = 'Gestion réseaux sociaux';
$ handle-> query ('SELECT social_networks FROM sale WHERE id_customer = "'. $ id. '" AND product = "'. $ product. '"');
In addition, the accented characters displayed in the view from the database are not displayed correctly.
However, the rest of the written text content that does not come from the database displays the accented characters.
I still put the meta:
<meta http-equiv = "Content-Type" content = "text / html; charset = UTF-8" />
So I deduce that it comes from the encoding of the database but it is identical to that of my former host (UTF8_unicode_ci)
What can be the reason for you?
Thank you in advance for your help !!
It was enough to add "charset=utf8" to PDO
new PDO("mysql:host=$this->host;dbname=$this->dbname;charset=utf8", $this->user, $this->password);

PDO_ODBC accessing IBM DB2 tables with special characters in the table names

I'm working on a DB2 table on as/400. I'm trying to run a basic query against it but the table name contains a . in it. For example: my.table is the table name.
The problem is that PDO believes that I'm specifying a database name my with my table name table. Hence the prepared statement is failing and saying no such table table exists in database my. Changing the table name is not an option.
What is the best way to handle a period in the table name? I've tried escaping the period but haven't had any success.
Here's some example code of my problem:
$sql= "select * from '[THE.TABLE]'";
try {
$statement = $this->db->query($sql);
$results = $statement->execute();
foreach ($results as $result) {
print_r($result);
}
exit;
}
catch (\Exception $e)
{
//log issue and other stuff
}
The application is running in Zend Framework 2.
I stand corrected. As aynber mentioned in a comment, the solution was to use double quotes escaped correctly. The answer could be found in the question directed towards MySQL.

"&" And "And" In A Prepared Statement Failing

I have this chunk of PHP code (abridged for brevity) as a prepared statement that allows the user to search through a database using a series title...
$series = null;
if (isset($_GET["series"])) $series = $_GET["series"];
try {
$dbh = new PDO("sqlsrv:Server=localhost;Database=Radio", "", "");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($series)) {
$sql = "SELECT *
FROM dbo.Schedule
WHERE dbo.Schedule.Series LIKE :series
ORDER BY dbo.Schedule.Date ASC";
}
$stmt = $dbh->prepare($sql);
if (isset($series)) {
$stmt->execute(array(":series" => $series));
}
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$dbh = null;
}
catch(PDOException $e) {
echo $e->getMessage();
}
It works perfectly fine for any series title that DOES NOT include &, but it fails (produces no results) for any series title that does.
For instance, Abounding Ability works but Receiving & Ministering Healing does not (even though both are in the Series field of the database.
I tried htmlspecialchars(rawurlencode($_GET["series"])) and each one individually.
On the SQL server, passing the same query (using the title) works just fine.
SELECT *
FROM [Radio].[dbo].[Schedule]
where Series like 'Receiving & Ministering Healing'
My guess is that the problem is in the execution of the prepared statement or in binding the parameters.
I did a search on PHP's Prepared Statements page for &, but didn't see any results.
Edit:
I used this to get it working...
$series = null;
if (isset($_GET["series"])) $series = $_GET["series"];
$queries = parse_url($_SERVER['QUERY_STRING']);
if (substr($queries["path"], 7) == "Receiving%20&%20Ministering%20Healing") $series = "Receiving & Ministering Healing";
I'm sure it's a terrible way to do it, but no other option was working. Of course, that only works in this particular case. I welcome a better solution.
Edit 2:
I found that a series with the WORD And in it (Graces And Places) presents the same issue. I ended up duplicating my "fix" for Receiving & Ministering Healing for it.
I doesn't seem to have anything to do with the URL query (or the word And wouldn't matter), but the prepared statement.
There can be multiple causes for this. The & character is evil on multiple levels, in this case, these two seem relevant:
It can be that your request looks like this (& signs highlighted under)
http://somedomain.com/somepage.php?param=something&series=Receiving & Ministering Healing
^ (valid) ^ (unintended!)
because the title is not escaped for URLs. This would mean that the & character marks a new parameter name - and would truncate the series to be Receiving instead of the full title Receiving & Ministering, resulting in the query:
SELECT *
FROM [Radio].[dbo].[Schedule]
where Series like 'Receiving '
You should probably show us how you assemble the URL for the request to be able to recommend more approporiate solution, but you should use urlencode() for escaping values to be used in GET parameters.
Or the problem could be (however it is not this case now) that you are writing the values wrongly.
A single & character is not valid in HTML! The correct escaping is &
You should HTML encode the output from the SELECT queries with htmlentities:
echo "<h1>".htmlentities($resultComingFromQuery)."</h1>";
EDIT
A bad request will likely result in a bad response (GIGO)... This:
http://www.flcbranson.org/api/radio/?series=Receiving%20%26%20Ministering Healing
is the proper request. This is URL encoded. You have to decode it:
$decodedTitle = urldecode($_GET['series']);
And use that in the query...

How to convert HTML code of Unicode to Real Unicode Character

Is there any php function that can convert
ابب
to it equallent unicode character
ت ب ا
I have googled a lot, But I think there is no any PHP built in function available for this purpose. Actually, I want to store the user submitted comments (that are in unicode characters) to mysql database. But It is stored in this format ابب in mysql database. I am also using SET NAMES 'utf8' in mysql query. The Output is in real unicode characters that is fine, but the insertion in mysql is in this format ابب that i don't want.
Any Solution??
I googled It and found a very interesing solution here
I have also tried it and I think Its working
<?php
$trans_tbl = get_html_translation_table(HTML_ENTITIES);
foreach($trans_tbl as $k => $v)
{
$ttr[$v] = utf8_encode($k);
}
$text = 'اب&#1576';
$text = strtr($text, $ttr);
echo $text;
?>
for mysql solution you can set the character set as
$mysqli = new mysqli($host, $user, $pass, $db);
if (!$mysqli->set_charset("utf8")) {
die("error");
}
if you
1 - set your html page's lang encoding to utf-8 which includes your forms
2 - only use your forms to enter input into your related MySQL db tables
3 - set all collations to utf8_unicode_ci in your MySQL (tables and rows collations)
4 - if you have premission you can also setyour MySQL DB collation as utf8_unicode_ci
then you won't see entities in your mySQL records also
This is my solution I use and have no trouble with my mother language which also has lots of unicode characters.
Below I introduce you my db connection php code & recommend (by using prepared statements; please check http://php.net/manual/en/mysqli.quickstart.prepared-statements.php)
//mysql bağlantısı
global $db_baglanti;
$db_baglanti = new mysqli(vt_host, vt_user, vt_password, vt_name);
if ($db_baglanti->connect_errno)
{
echo "MySQL bağlantısı kurulamadı: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!$db_baglanti->set_charset("utf8"))
{
printf("utf8 karakter setinin yüklenmesinde problem oluştu: %s\n", $db_baglanti->error);
}
else
{
$db_baglanti->set_charset("utf8");
}
I think you should be able to use mysql_set_charset() http://php.net/manual/en/function.mysql-set-charset.php to set the mysql connection encoding so when you retrieve these from the DB and display them they should be fine.
According to php.net "This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used."

Categories