0

I am getting this warning and the php returns null .

PHP Warning: json_encode(): Invalid UTF-8 sequence in argument in /var/www/rreadyreckoner/get_instruction.php on line 26 {"result":[{"instruction":null}]}

I am trying to run this php script.

<?php 
include "demo_config.php";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$dbname);
 if(!$con)
 {
         echo "Connection Error".mysqli_connect_error();
 }
 else{
//echo "";
 }

$query ="SELECT instruction FROM `rreadyreckoner` ORDER BY id DESC LIMIT 1;";

$res = mysqli_query($con,$query);
$result = array();
while($row = mysqli_fetch_array($res))
{
                  array_push($result,
                  array('instruction'=>$row[0]));
}
if(!$result)
{
echo "Nothing to display";
}else
{
echo json_encode(array("result"=>$result));
}
mysqli_close($con);
?>

The only change I did was when inserting content into mysql database removed a character that was getting inserted by default and replaced it with nothing.

$instruction =$_POST["instruction"];
$plainHTML = str_replace(chr(194),"",$instruction);
$sql = "INSERT INTO rreadyreckoner (id, instruction)
VALUES (NULL, '$plainHTML')";

Before doing this I was getting a proper response. Any help or suggestion is appreciated. Thank you.

AndroidNewBee
  • 744
  • 3
  • 12
  • 36

2 Answers2

1

Simply add this:

mysqli_set_charset($con, "utf8");

after mysql connect.

Noman
  • 1,459
  • 2
  • 18
  • 38
  • This adds {"result":[{"instruction":"\n\n\u00a0 \u00a0<\/head>\n\n\u00a0 \u00a0\n\n\u00a0 \u00a0 \u00a0 and \n characters how can I get rid of them. – AndroidNewBee Aug 22 '16 at 06:45
  • Have you saw that answer of Stack Overflow http://stackoverflow.com/a/30363698/3081659 – Noman Aug 22 '16 at 06:52
0
$t = json_encode($s, JSON_UNESCAPED_UNICODE);

avoids the \u.... stuff.

Don't use mb_encode, etc.

194 is hex C2 which is a common first byte in utf8 sequences.

See Trouble with utf8 characters; what I see is not what I stored for more discussion on what needs to be done. In particular, check the SELECT HEX... technique to see if data is stored correctly.

Back to the title... Can you provide the invalid sequence you are dealing with? You can do something like echo bin2hex(...) to get the hex of the naughty string.

Community
  • 1
  • 1
Rick James
  • 135,179
  • 13
  • 127
  • 222