JSON not generating while VAR_DUMP shows results [duplicate] - php

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";

Related

Json encode not able to fetch special characters from db in 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"
}
}
}

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);

PHP foreach loop through array

I have a fairly big array that I source from Facebook:
array(25) {
[0]=>
array(14) {
["id"]=>
string(31) "245226895508982_651884328176568"
["from"]=>
array(2) {
["name"]=>
string(16) "Madeleine Björs"
["id"]=>
string(15) "100002249777453"
}
["to"]=>
array(1) {
["data"]=>
array(1) {
[0]=>
array(2) {
["name"]=>
string(31) "Wohnung/WG in München gesucht!"
["id"]=>
string(15) "245226895508982"
}
}
}
Now what I want to do is go through the array and save ID, name and various other information from that array into a mysql database. However, to understand how to target specific information I tried to echo the data first.
$data = json_decode(file_get_contents('https://graph.facebook.com/'), true);
foreach($data as $item) {
echo $item['id'];
echo '<pre>'; var_dump($item);
}
This PHP code is based on various posts on Stackoverflow, however, the code returns nothing. May you please help me to target the arrays appropriately? You may check the enire array here: http://faculty-fight.de/milliondollaridea/facebook_session.php
Cheers!
foreach($array as $key=>$subArray)
{
foreach($subArray as $subKey=>subSubArray)
{
if(is_array($subSubArray))
{
foreach($subSubArray as $subSubKey=>$value)
{
if(is_array($value))
{
foreach($value as $valueKey=>$subValue)
{
/* your code /*
}
}
}
}
}
you can check for id values for example for 1st loop (if($subKey == "to")).

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
}
}

xml foreach skipping over if statement in php

Here's what I am trying to achieve.
I am importing an xml file of products (the product tag has an id attribute:
as an example.
There is 1 tag (category) inside the product tag that I am trying to retrieve but I only want one instance of it. So I created a flag to help distinguish when the product id changes.
My code looks like this
<?php
$flag='start';
foreach($xml->product as $product)
{
$attrs = $product->attributes();
echo "$attrs ($flag)"; // just used for testing results
if ($flag != $attrs) {
echo "| <a href='xmltest.php?menuitem=$attrs'>".$product->category." </a><br>";
$flag=$attrs;
}
}
?>
What should happen on the first run is the flag doesn't match the attrs, the link is echoed, the flag now matches the attrs.
If I have 5 product tags with ID's of 1,1,2,2,2, the code should echo the link twice (first when $flag=start while $attrs=1, and when $flag=1 while $attrs=2)...
Instead, it echoes it all 5 times, basically ignoring the if statement.
I can't see where I am going wrong with the if statement. Can anyone help?
Update Thanks Showerhead, I have been trying your suggestions and I am a bit closer than before.
I did the var_dump and the result I am seeing looks like this
flag var_dump result:string(5) "start"
attrs var_dump result: object(SimpleXMLElement)#6 (1) { ["#attributes"]=> array(1) {
["id"]=> string(1) "0" } } 0 (0)
flag var_dump result:object(SimpleXMLElement)#6 (1) { ["#attributes"]=> array(1) {
["id"]=> string(1) "0" } }
attrs var_dump result: object(SimpleXMLElement)#5 (1) { ["#attributes"]=> array(1) {
["id"]=> string(1) "0" } } 0 (0)
flag var_dump result:object(SimpleXMLElement)#5 (1) { ["#attributes"]=> array(1) {
["id"]=> string(1) "0" } }
attrs var_dump result: object(SimpleXMLElement)#4 (1) { ["#attributes"]=> array(1) {
["id"]=> string(1) "0" } } 1 (0)
flag var_dump result:object(SimpleXMLElement)#4 (1) { ["#attributes"]=> array(1) {
["id"]=> string(1) "0" } }
attrs var_dump result: object(SimpleXMLElement)#8 (1) { ["#attributes"]=> array(1) {
["id"]=> string(1) "1" } } 1 (1)
flag var_dump result:object(SimpleXMLElement)#8 (1) { ["#attributes"]=> array(1) {
["id"]=> string(1) "1" } }
I understand now how the $flag var starts off as a string and then adopts the value of the array.
I tried if( ! is_array($flag) && $flag != $attrs) { but the results were the same.
Is there another way I can get the values to be similar for comparison?
Thanks again,
UPDATE
a simple explode helped solve it. Here is the code that is working for me.
<?php
$flag='start';
foreach($xml->product as $product)
{
$category = $product->category;
$attrsvar = $product->attributes();
$attrs = explode(" ", $attrsvar);
if( ! is_array($flag) && $flag != $attrs[0]) {
echo " <a href='xmltest.php?menuitem=".$attrs[0]."'>".$category." </a> | ";
$flag=$attrs[0];
}
}
?>
You are going to want to make sure it is not an array first.
if( ! is_array($flag) && $flag != $attrs) { etc... }
There that should be it, sorry if you were reading first post before I edited it. I completely misread your problem. Now the reason this should work is because you were originally trying to compare an array to a string, which was probably throwing silent errors.
Edit: If its still not working try var_dump() to make sure both variables are the same type when they are being compared.
Update: You know what, we are both over thinking this. I will assume you are doing something with this XML other than just getting categories, otherwise you can look into the much simpler XPATH solution below. If you are doing something more with this XML you could just do the following.
$products = array();
foreach($xml->product as $product) {
$id = $product['id'];
$category = $product->category;
if( ! in_array($id, $products)) {
$products[$id] = $category;
echo "| <a href='xmltest.php?menuitem=$attrs'>".$category." </a><br>";
}
}
XPATH for if you just want to work with categories. Let me know if my XPATH is not quite right, I'm not too good with it under normal circumstances, I'd hate to think how badly I could mangle it under sleep depravation.
$categories = $xml->xpath('//product/category');
$categories = array_unique($categories);
foreach($categories as $category) {
echo "| <a href='xmltest.php?menuitem=$attrs'>".$category." </a><br>";
}

Categories