Json encode not able to fetch special characters from db in php - php

I am learning to write ANDROID API in PHP to fetch data from the server.
The table in the server has a column "name" with value "Jàne" already present.
Below is the sample code:
<?php
$reply= array();
if(isset($_POST['place'])){
// DB connection
$place= $mySQLiconn->real_escape_string($_POST['place']);
$search= $mySQLiconn->query("SELECT name, id FROM info WHERE addr = '$place'");
if(!empty($search)){
if($search->num_rows > 0) {
$reply["list"]= array();
while($search = $search->fetch_array()){
$row = array();
$row["id"] = $search["id"];
$row["name"] = $search["name"];
array_push($reply["list"], $row);
}
echo json_encode($reply);
} else{
//
$reply["msg"] = "Error";
echo json_encode($reply);
}
} else{
//Fetched failed
$reply["msg"] = "Error";
echo json_encode($reply);
}
$mySQLiconn->close();
} else {
$reply["msg"] = "Error";
echo json_encode($reply); // point L
}
?>
If the result from the search result contains any special character, I get a 200 reply with a BLANK response body.
If the search result contains only A-Z, a-z, 0-9, comma, space ; then its working, I get a proper response body.
Please help me how to fetch the data with special character also.
EDIT
I want the same exact data in my response also, so that I can show it in the app UI.
There are other special characters also in the table like é , è , à, etc
Select command is working properly in my cpanel for special character also
So, I think its not a database issue.
UPDATE:
The current code returns blank, but if i replace point L with echo var_dump($reply);
I get the response in following format:
array(1) {
["list"]=> array(3) {
[0]=> array(2) {
["id"]=> string(2) "31"
["name"]=> string(4) "Maze"
}
[1]=> array(2) {
["id"]=> string(2) "35"
["name"]=> string(4) "Jan�"
}
[2]=> array(2) {
["id"]=> string(2) "39"
["name"]=> string(7) "Puchong"
}
}
}

Related

JSON not generating while VAR_DUMP shows results [duplicate]

This question already has answers here:
PHP json encode - Malformed UTF-8 characters, possibly incorrectly encoded [duplicate]
(9 answers)
json_decode returns NULL, json_last_error_msg gives "Control character error, possibly incorrectly encoded"
(1 answer)
UTF-8 all the way through
(13 answers)
Closed 3 years ago.
I am trying to generate JSON using PHP and SQLSRV. But it seems json_encode is not returning any results while var_dump shows the results. I am unable to figure out what's wrong with my code. I am using WAMP 2.0 under windows environment.
<?php
require_once '../inc/sql.php';
require_once '../inc/functions_sola.php';
?>
<?php
$ConnectionInfo=dbConnectDBServer();
if ($ConnectionInfo == false) {
die( print_r( sqlsrv_errors(), true));
}
$query1 = $SOLAEntityDetails;
$temp = array();
if (($result = sqlsrv_query($ConnectionInfo,$query1)) == null) {
die(print_r(sqlsrv_errors(), true));
echo "into result fail ";
}
else
{
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
{
$temp[] = $row;
}
}
#var_dump($temp, json_encode($temp));
echo json_encode($temp);
sqlsrv_close($ConnectionInfo);
?>
I've commented out var_dump but it shows results fine.
var_dump($temp) results below:
array(5) { [0]=> array(2) { ["EntityID"]=> int(466) ["Name"]=> string(20) "A.R.T. Advisors, LLC" } [1]=> array(2) { ["EntityID"]=> int(210) ["Name"]=> string(14) "Abbey National" } [2]=> array(2) { ["EntityID"]=> int(211) ["Name"]=> string(25) "Aberdeen Asset Management" } [3]=> array(2) { ["EntityID"]=> int(209) ["Name"]=> string(25) "ABN AMRO Clearing Bank NV" } [4]=> array(2) { ["EntityID"]=> int(209) ["Name"]=> string(25) "ABN AMRO Clearing Bank NV" } }
SQL query is as below:
$SOLAEntityDetails="
select top 5 en.EntityID, en.Name
from SolaDBServer..tblClientLicense cl
LEFT JOIN tblClientLicenseDetail cd ON cd.ClientLicenseID = cl.ClientLicenseID
LEFT JOIN tblEntity en ON en.EntityID = cl.EntityID
LEFT JOIN tblClientMarketDataContact mdc ON mdc.ClientLicenseID = cl.ClientLicenseID
Order By en.Name asc";

Why do JSON values not display in PHP?

I am working PHP and MySQL. I am created a database and table. I want to convert table to JSON. So, I write this code block:
<?php
include "../config/database.php";
$SQLUser = "SELECT * FROM tbl_user";
$SQLUserResult =mysqli_query($Conn,$SQLUser );
$JSON= array();
while($row=mysqli_fetch_assoc($SQLUserResult ))
{
$JSON[] = $row;
}
$Show = json_encode($JSON);
echo count($JSON);
echo $Show;
?>
When run this page, I take JSON size correctly. But I can't display JSON values. What can I do?
In the page source, I see the count of rows in my JSON array (13), but no data.
Adding var_dump($row); shows me something like
array(13) { [0]=> array(3) { ["id"]=> string(1) "1" ["name"]=> string(1) "A" ["surname"]=> string(1) "A" } [1]=> array(3) { ...
The encoding is utf8_general_ci.
I think, your database or tables returns probably a faulty response, some strings were probably not UTF-8. So, You can create a function for convert UTF-8.
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} else if (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}
Than, you can encode just like this:
echo json_encode(utf8ize($JSON));

How to add data to OBJECT from Wordpress get_results in PHP

Seems really easy, but I can't seem to figure it out...
I have a simple line that gets mysql results through wordpress like this:
$sql_results = $wpdb->get_results($sql_phrase);
Then I parse it as JSON and echo it: json_encode($sql_results);
However, I want to add other data before I parse it as JSON. But I'm not sure how.
$sql_results basically gets me a list of post ID's, title and category.
It looks like this in var_dump (this is just the first row):
array(1)
{
[0]=> object(stdClass)#2737 (7)
{
["ID"]=> string(4) "2700"
["post_title"]=> string(18) "The compact helmet"
["category"]=> string(5) "Other"
}
}
Now to start with something easy, I'd like all associative arrays inside the object to have the extra key-value. I tried the following but got an error:
500 Internal error.
foreach($sql_search as $key => $value)
{
$value['pic_img'] = "test";
$sql_search[$key]=$value;
}
$result=$sql_search;
$sql_results = array(1)
{
[0]=> object(stdClass)#2737 (7)
{
["ID"]=> string(4) "2700"
["post_title"]=> string(18) "The compact helmet"
["category"]=> string(5) "Other"
}
}
foreach($sql_results as $key=>$value)
{
$value->solution = 'good';
$sql_results[$key]=$value;
}
$result=$sql_results;
var_dump($result);
$test = array ( array("ID"=>"35", "name"=>"Peter", "age"=>"43"),
array("ID"=>"34", "name"=>"James", "age"=>"19"), array("ID"=>"31", "name"=>"Joe", "age"=>"40") );
foreach($test as $key=>$value)
{
$value['solution'] = 'good';
$test[$key]=$value;
}
$result=$test;
var_dump($result);

check string in array for special characters

I have got an array wich contains several strings like this:
array(133) {
[0]=>
array(1) {
["row"]=>
array(5) {
[0]=>
string(10) "testd ' /% ata"
[1]=>
string(14) "testdata 111"
[2]=>
string(17) "testdata 123"
[3]=>
string(0) ""
[4]=>
string(0) ""
}
}
[1]=>
array(1) {
["row"]=>
array(5) {
[0]=>
string(9) "198"
[1]=>
string(14) "testdata"
[2]=>
string(41) "testdat"
[3]=>
string(0) ""
[4]=>
string(0) ""
}
}
My question is how can I check the strings within the array on special chars? These special chars are causing a syntax error when importing into my DB.
I think i need to use something like this?
preg_replace('/[^a-zA-Z0-9_ -%][().][\/]/s', '', $String);
Can anyone help me on this one?
Allright nog i have created this piece of code:
// search for special chars in the import data and remove them
$illegal = "#$%^&*()+=-[]';,./{}|:<>?~";
foreach ($data_set as $data)
foreach ($data_set['data'] as $row) {
if(strpbrk($row, $illegal)) {
echo($row);
die();
}
else {
//not allowed ,escape or do what you want
echo("no characters found");
die();
}
var_dump($row);
die();
}
But this still gives an error:
A PHP Error was encountered
Severity: Warning
Message: strpbrk() expects parameter 1 to be string, array given
Filename: controllers/import.php
Line Number: 153
no characters found
You may have a look at strpbrk. It should solve your problem.
Example:
$tests = "testd ' /% ata";
);
$illegal = "#$%^&*()+=-[]';,./{}|:<>?~";
echo (false === strpbrk($test, $illegal)) ? 'Allowed' : "Contains special chars";
But i suggest to escape your strings before inserting to database,it's much safer.
foreach ($yourArray as $array)
foreach ($array['row'] as $row) {
if(strpbrk($row, $illegal)) {
//allowed ,insert to db
}
else {
//not allowed ,escape or do what you want
}
}

PHP Array not accessible

Basically, i'm trying to get users data from a database using a class i found, it's parsing all data inside an array as shown here from the following function :
public function Get($field = NULL) {
if ($field == NULL)
{
$data = array();
while ($row = mysql_fetch_array($this->last_query))
{
$data[] = $row;
}
}
else
{
$row = mysql_fetch_array($this->last_query);
$data = $row[$field];
}
return $data;
}
Here's the PHP code i'm using to get the call this function
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if($_SESSION['csrfToken'] == $_POST['csrfToken']) {
$email = $_POST['email'];
$password = $Security->Salt($Security->secParam($_POST['password']));
$DB->Query("SELECT * FROM `table` WHERE `email` = '$email' AND `password` = '$password'");
if($DB->num_rows() > 0) {
$results = $DB->Get();
} else {
echo "Account not found";
}
}
}
If i do a var_dump on $results it shows the following
array(1) {
[0]=> array(8) {
[0]=> string(1) "1" ["id"]=> string(1) "1"
[1]=> string(35) "email#email.com" ["email"]=> string(35) "email#email.com"
[2]=> string(32) "4f14dfef1efe0de64e2b176eac6051cd" ["password"]=> string(32) "4f14dfef1efe0de64e2b176eac6051cd"
[3]=> string(1) "1" ["status"]=> string(1) "1"
}
}
how can i access this data ? I've tried calling it by doing the following
$email = $results['email'];
echo $email;
But it's not displaying anything ?
Even though there's only one result in this instance (I guess?) the array supports multiple.
So find the first result, then take the email from that:
echo $results[0]['email'];
// ^^^^^^^^^^^
// first result
You need to tracking how arrays works. First you have array(1) and then into array another vars such as "email" or 1.
array(1) { <---- THIS IS ARRAY OCCURED FOR FIRST "0" ARRAY.
What's about
this
\/
echo $results[0]["email"]; ?
if($_SERVER['REQUEST_METHOD'] == 'POST' && $_SESSION['csrfToken'] == $_POST['csrfToken']) {
$password = $Security->Salt($Security->secParam($_POST['password']));
$password = $DB->quoteStr($password);
$email = $DB->quoteStr($_POST['email']);
$DB->Query("SELECT * FROM `table` WHERE `email` = $email AND `password` = $password");
return $DB->GetRow();
}
public function GetRow() {
return mysql_fetch_array($this->last_query);
}
public function quoteStr($str) {
return "'".mysql_real_escape_string($str)."'";
}
Marin Sagovac question is the answer.
To break it down a little more, your var_dump output shows that $results is a nested array. The first part of the output:
array(1) {
[0]=>
shows that $results consists of an array containing 1 element, at index 0, since that's where PHP starts indexing. This is the $results[0] part of Marin's response.
The element 0 of the $results array consists of an array with 8 elements.
[0]=>array(8) {
[0]=> string(1) "1" ["id"]=> string(1) "1"
[1]=> string(35) "email#email.com" ["email"]=> string(35) "email#email.com"
Even though there are only 4 actual results, index 1-4, each one exists twice so that they can either be accessed by index or by its key. Arrays that can be accessed by a unique key, as opposed to an index, are known as associative arrays.
So, in this case, either will return the same value:
echo $results[0]["email"];
echo $results[0][1];
The print_r function would also work, instead of var_dump.

Categories