Convert MySQL to Json ResultSet - php

I'm trying to turn my results into a json encoded string. I know that now working on an external api seems a bit much, but I do think that it's something that will come in handy as times goes on. Currently, I use the following function:
//API Details
public function APIReturnMembers() {
$query = <<<SQL
SELECT uname
FROM {$this->tprefix}accounts
SQL;
$encode = array();
$resource = $this->db->db->prepare( $query );
$resource->execute();
foreach($resource as $row) {
$encode[] = $row;
}
echo json_encode($encode);
}
It does what it's supposed to as far as returning results go, e.g.:
[{"uname" : "guildemporium"}, {"uname" : "doxramos"}]
When I saw that I was ecstatic! I was on my way to implementing my own API that others could use later on as I actually got somewhere! Now of course I have hit a hickup. Testing my API.
To run the code to get the results I used
$api_member_roster = "https://guildemporium.net/api.php?query=members";
$file_contents = #file_get_contents($api_member_roster); // omit warnings
$memberRoster = json_decode($file_contents, true);
print_r($memberRoster);
The good news!
It works. I get a result back, yay!
Now the Bad.
My Result is
[
0 => ['uname' => 'guildemporium'],
1 => ['uname' => 'doxramos']
]
So I've got this nice little number integer interrupting my return so that I can't use my original idea
foreach($memberRoster as $member) {
echo $member->uname;
}
Where did this extra number come from? Has it come in to ruin my life or am I messing up with my first time playing with the idea of returning results to another member? Find out next time on the X-Files. Or if you already know the answer that'd be great too!

The numbered rows in the array as the array indices of the result set. If you use print_r($encode);exit; right before you use echo json_encode($encode); in your script, you should see the exact same output.
When you create a PHP array, by default all indices are numbered indexes starting from zero and incrementing. You can have mixed array indices of numbers and letters, although is it better (mostly for your own sanity) if you stick to using only numbered indices or natural case English indices, where you would use an array like you would an object, eg.
$arr = [
'foo' => 'bar',
'bar' => 'foo'
];
print_r($arr);
/*Array
(
[foo] => bar
[bar] => foo
)*/
$arr = [
'foo','bar'
];
/*Array
(
[0] => foo
[1] => bar
)*/
Notice the difference in output? As for your last question; no. This is normal and expected behaviour. Consumers will iterate over the array, most likely using foreach in PHP, or for (x in y) in other languages.
What you're doing is:
$arr = [
['abc','123']
];
Which gives you:
Array
(
[0] => Array
(
[0] => abc
[1] => 123
)
)
In order to use $member->foo($bar); you need to unserialize the json objects.

In you api itself, you can return the response in json object
In your api.php
function Execute($data){
// Db Connectivity
// query
$result = mysqli_query($db, $query);
if( mysqli_num_rows($result) > 0 ){
$response = ProcessDbData($result);
}else{
$response = array();
}
mysqli_free_result($result);
return $response;
}
function ProcessDbData($obj){
$result = array();
if(!empty($obj)){
while($row = mysqli_fetch_assoc($obj)){
$result[] = $row;
}
return $result;
}
return $result;
}
function Convert2Json($obj){
if(is_array($obj)){
return json_encode($obj);
}
return $obj;
}
Calling api.php
$result = $this->ExecuteCurl('api.php?query=members');
print_r($result);
here you $result will contain the json object

Related

How to get "variable" of Response Object

I'm using an API in PHP that when I call one function it prints:
PagSeguro\Parsers\Transaction\CreditCard\Response Object
(
[date:PagSeguro\Parsers\Transaction\Response:private] => 2021-11-04T21:10:12.000-03:00
[code:PagSeguro\Parsers\Transaction\Response:private] => X
[reference:PagSeguro\Parsers\Transaction\Response:private] => Y
[...]
I need to get the code:PagSeguro\Parsers\Transaction\Response:private result but I didn't find out how. To call this response the line is: $result = $creditCard->register(\PagSeguro\Configuration\Configure::getAccountCredentials());
Here's the code that I did to make it work.
try {
//Get the crendentials and register the boleto payment
$result = $creditCard->register(
\PagSeguro\Configuration\Configure::getAccountCredentials()
);
$array = (array) $result; // makes it a "normal" array
$values = array_values($array); // get all those values
$transactionid = $values[1]; // returns the second value

I can't access specific indexes of my array php

I can't access specific indexes of my array, I want access to the third index of the array that actually holds the zip code of the user to use it in a SELECT statement. Here's the array:
$zip_code = connecting::query('SELECT zipcode FROM accounts WHERE username=:user_name', array(':user_name' => $user_name));
$zipcode = json_encode($zip_code, true);
Here's the output when I print $zipcode:
[{"zipcode":"28262","0":"28262"}]
But when I print $zipcode[2] nothing prints and I can't use it. I can't just access it directly like that? I have used json_encode, var_export, implode, etc. to try to just convert it to a string but it doesn't work.
Here's the query method that I call:
public static function query($query,$params = array())
{
$statement = self :: db()->prepare($query);
$statement->execute($params);
if(explode(' ',$query)[0] == 'SELECT')
{
$data = $statement->fetchAll();
return $data;
}
}
fetchAll returns array of arrays. So, if you print_r(zip_code); you will see something like:
Array (
[0] => Array (
[zipcode] => 28262
[0] => 28262
)
)
So, as you can see - there's no key with index 2 here, only 0 in the outer array and two keys 0 and zipcode in the subarray.
Also, as you can see your data (28262) is duplicated in the subarray under different keys. To avoid this you can provide argument to fetchAll:
$data = $statement->fetchAll(PDO::FETCH_ASSOC);

Convert string to array in API call

I am passing an array as a string in parameter to an api in php like this:
http://xx.xx.xx.xx/api.php?query="array(done = 1)"
In my api file, I have used this array to hit a mongodb query:
$query = $_REQUEST['query'];
$cursor = $collection->find($query);
But this didn't work. When I hard-coded array(done = 1) into the find query, it seems to work fine.
if (array('done' => 1) == $query) {
echo "Y";
}
else {
echo "N";
}
The above code prints N. So I guess it's because $query is being passed as a string.
PS: I also tried json_encode, json_decode and unserialize but it didn't work. I might be doing omething wrong here.
Well make bit change in your query string, you passing in api request.
Suppose belowis your array.
$array = array('done' => 1, 'message' => 'success');
USE array_map_assoc function with some customization, which make easy to implode associative array
function array_map_assoc( $callback , $array ){
$r = array();
foreach ($array as $key=>$value)
$r[$key] = $callback($key,$value);
return $r;
}
Generate your data to be sent in api
our data
$queryString = implode('&',array_map_assoc(function($k,$v){return "$k=$v";},$array));
Now send your data with API
$url = "http://xx.xx.xx.xx/api.php?" . $queryString ;
Now use print_r($_GET) in your API page and you will receive data like below
Array
(
[done] => 1
[message] => success
)
This make your code easy to handle and use in either if condition or sql query.

Converting complexObjectArray to a Usable Array

I have a script which has output which looks like the following:
Which is something I've not experienced before. Normally the result would be the array and then the stdClass Object which I convert to an array using (array) $result. This one seems to be nested an extra 2 times however, so I have no idea how to access it so that I can turn each of those objects into an array.
So what I need to be able to achieve, for example, is that if I use the code echo $orders[0]->customer_id, the result would be 716'.
Could anybody please advise? My code is below if required. Thank you very much.
<?php
$client= new SoapClient('*Magento URL*');
$session_id = $client->login((object)array('username' => '*Magento Username*', 'apiKey' => '*Magento Password*'));
try {
$result = $client->salesOrderList((object)array('sessionId' => $session_id->result, 'filters' => null));
$orders = (array) $result;
echo '<pre>', print_r($orders), '</pre>';
} catch (SoapFault $e) {
echo 'Error: ', $e->getMessage(), '<hr>';
}
?>
$result is an object with a result property which is an object with a complexObjectArray property that is an integer indexed array of objects. So:
$orders = $result->result->complexObjectArray;
Then:
echo $orders[0]->customer_id;
If there is more than one item in the array then you would need to loop over it. If there is only ever one then include the 0 when defining $orders:
$orders = $result->result->complexObjectArray[0];
Then:
echo $orders->customer_id;

How to parse JSON array of objects in PHP

I am new to php programming. Here in my project I am trying to parse JSON data coming from php web service. Here is the code in web service.
$query = "select * from tableA where ID = 1";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
$arr= array();
while ($row = mysql_fetch_assoc($result)) {
$arr['articles'][] = $row;
}
header('Content-type: application/json');
echo json_encode($arr);
}
else{
echo "No Names";
}
This is giving me data in this JSON format.
{"articles":[{"ID":"1","Title":"Welcome","Content":"This is the first article."}]}
Now here is my php page code.
<?php
$jfile = file_get_contents('http://localhost/api/get_content.php');
$final_res = json_decode($jfile, true) ;
var_dump( $final_res );
$content = $final_res->articles->Content;
?>
I want to show the content on webpage.
I know code at var_dump( $final_res ); is working. But after that code is wrong. I tried to look at many tutorials to find the solution but didn't find anyone. I don't know where I am wrong.
The second parameter of json_decode determines whether to return the result as an array instead of an object. Since you set it to true your result is an array and not an object.
$content = $final_res['articles'][0]['Content'];
As an alternative answer, if you want to use it as an object, use this code:
$a = '{"articles":[{"ID":"1","Title":"Welcome","Content":"This is the first article."}]}';
$final_res = json_decode($a);
echo '<pre>';
print_r($final_res);
echo '</pre><br>';
Note that I removed the second part (true) from the json_decode
Output:
stdClass Object
(
[articles] => Array
(
[0] => stdClass Object
(
[ID] => 1
[Title] => Welcome
[Content] => This is the first article.
)
)
)
Accessing Content:
echo 'Content: ' . $final_res->articles[0]->Content;
Output:
Content: This is the first article.
Run code

Categories