0

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�,

Mickaël Leger
  • 3,426
  • 2
  • 17
  • 36
Philip
  • 24
  • 6
  • If you run the SELECT query on phpmyadmin (or through the command line), do you get the correct output, with single quotes in tact? – Reed Jun 05 '19 at 14:33
  • And you escape with a backslash like `$mystr = "he said \"i want food\" yesterday"`. I don't think that's your problem though – Reed Jun 05 '19 at 14:35
  • 1
    `$db->query("SET NAMES 'utf8'");` – m1k1o Jun 05 '19 at 14:41
  • 1
    @Reed, yes pls..select query on phpmyadmin gives me a correct output however i get a different output in the browser. – Philip Jun 05 '19 at 14:42

1 Answers1

1

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.

Sergio Rinaudo
  • 2,303
  • 15
  • 20