How to add array items in one single item? - php

this is the code I am working on. I am creating an API for my mobile device.
<?php
$property_id=$_GET['property_id'];
$res_image=mysql_query("select *
from fak_property_image
where property_id='".$property_id."'");
$i=0;
while($row2=mysql_fetch_array($res_image)){
// $status[$i]['property_id']=$row2['property_id'];
// $status[$i]['image']=$row2['image'];
$status[$i]['path']=$row2['path'];
$i++;
}
echo json_encode( $status );exit;
?>
the output is following
[
{"path":"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_0008.1525441844.JPG"},
{"path":"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_0009.1525441844.JPG"},
{"path":"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_0013.1525441844.JPG"},
{"path":"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_0015.1525441844.JPG"},
{"path":"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_0016.1525441844.JPG"},
{"path":"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_0074.1525441844.JPG"},
{"path":"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_0210.1525441844.JPG"},
{"path":"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_0211.1525441844.JPG"},
{"path":"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_1400.1525441844.JPG"},
{"path":"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_1903.1525441844.jpg"},
{"path":"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_1904.1525441844.jpg"},
{"path":"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_1905.1525441844.jpg"},
{"path":"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_1906.1525441844.jpg"}
]
but my requirement is to display the output like this
[
{
"path":
"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_0008.1525441844.JPG",
"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_0009.1525441844.JPG",
"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_0013.1525441844.JPG",
"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_0015.1525441844.JPG",
"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_0016.1525441844.JPG",
"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_0074.1525441844.JPG",
"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_0210.1525441844.JPG",
"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_0211.1525441844.JPG",
"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_1400.1525441844.JPG",
"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_1903.1525441844.jpg",
"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_1904.1525441844.jpg",:
"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_1905.1525441844.jpg",
"http:\/\/grandthecompany.com\/admin\/uploads\/IMG_1906.1525441844.jpg"
}
]
I have tried to fetch all the data using mysql_fetch_all but it is not working. Please help.
Thanks

Try the following:
$status['path'][] = $row2['path'];
Instead of:
$status[$i]['path']=$row2['path'];
But you definitely should use PDO, besides this code is vulnerable for SQL injections.

Related

How to obtain a value from a multidimensional json array

i'm entirely new to this site, so i'm sorry in advance if my post is not formatted properly.
Anyway, i have what i expect to be a fairly simple question. I'm extracting values from a "request body"-array-thingy, and i got most of what i need by using these 4 lines of code:
$payment_id = strval($callback_json->id);
$order_id = strval($callback_json->order_id);
$currency = strval($callback_json->currency);
$card_brand = strval($callback_json->metadata->brand);
My problem now is that i've run out talent when trying to get the "amount" value that seems to be a "sub-variable" to "operations".
I've tried doing it like this, but neither of them work:
$amount_total = strval($callback_json->operations[amount]);
$amount_total = strval($callback_json->operations->amount);
So my question now is; How do i format this line to get the value "69500".
I really hope someone out there can help me! :-)
{
"id":9256797,
"order_id":"23322651466",
"accepted":true,
"type":"Payment",
"text_on_statement":null,
"branding_id":null,
"variables":{},
"currency":"DKK",
"state":"new",
"operations":[{
"id":1,
"type":"authorize",
"amount":69500,
"pending":false,
"qp_status_code":"20000",
"qp_status_msg":"Approved",
"aq_status_code":"20000",
"aq_status_msg":"Approved",
"data":{},
"callback_url":"http://requestb.in/105y8k81",
"callback_success":null,
"callback_response_code":null,
"created_at":"2015-12-05T12:40:40+00:00"
}],
"metadata":{
"type":"card",
"brand":"visa",
"last4":"0008",
"exp_month":11,
"exp_year":2016,
"country":"DNK",
"is_3d_secure":false,
"hash":"6f976a4e388928beb4ad3OrQHCS2LDGNAFZVK3i54p6q8heV0RRci",
"number":null,
"customer_ip":"2.110.77.40",
"customer_country":"DK",
"fraud_suspected":false,
"fraud_remarks":[]
}
use
$amount_total = strval($callback_json->operations[0]->amount);
because [ in json is an open tag for an array.
{'foo':[{'bar':"A"},{'bar':"B"}]}
$val->foo[0]->bar; # A
$val->foo[1]->bar; # B
Hope that helps.

log a stock/share price variable to database useing php

i have an API that retrieves stock price data through a PHP script. I have tried several different ways to add the price
to my database with no luck.
please help as this is driving me crazy, I have tried logging it as a float with different syntax but still doesn't display,
please could you be kind enough to give me an example using the code below as i am completely new to PHP/mysqli and programing in general.
thanks.
please note that I use import.io to create the API and have removed the API key.
This is how the API works:
<?PHP
$url = 'http://my api url.com';
$json =file_get_contents($url);
$retVal =json_decode($json, TRUE);
$output = "<ul>";
foreach($retVal['results'] as $results) {
$output .="<p>".$results['price/_source']."</p>";
}
$output .="</url>";
echo $output; // this would show the price like so: 1.139791
?> '
//this is the json file.
{
"offset": 0,
"results":
[
{
"price": "1.140 293"
}
`]`,
"cookies": [ ],
"connectorVersionGuid": "2af429a0-3fa4-4e67-b9bf-fbf453674ccb",
"connectorGuid": "87343523-d4c8-47db-b582-5408be1b679b",
"pageUrl": "http://www.x-rates.com/calculator/?from=EUR&to=USD&amount=1",
"outputProperties":
[
`{`
`"name": "price",`
`"type": "STRING"`
`}`
`]`
}

Instagram Real time API - PHP - Unable to get POST Update

I'm trying to connect with the instagram API, the connection works fine and I am receiving the updates just as described in the API documentation, the issue is that I cannot access to the data send to my callback function.
According to the doc
When someone posts a new photo and it triggers an update of one of your subscriptions, we make a POST request to the callback URL that you defined in the subscription
This is my code :
// check if we have a security challenge
if (isset ($_GET['hub_challenge']))
echo $_GET['hub_challenge'];
else // This is an update
{
// read the content of $_POST
$myString = file_get_contents('php://input');
$answer = json_decode($myString);
// This is not working starting from here
$id = $answer->{'object_id'};
$api = 'https://api.instagram.com/v1/locations/'.$id.'/media/recent?client_secret='.INSTA_CLI_SECRET.'&client_id='.INSTA_CLI_ID;
$response = get_curl($api); //change request path to pull different photos
$images = array();
if($response){
$decode = json_decode($response);
foreach($decode->{'data'} as $item){
// do something with the data here
}
}
}
Displaying the $myString variable I have this result, don't know why it is not decoded to json :(
[{"changed_aspect": "media", "subscription_id": 2468174, "object":
"geography", "object_id": "1518250", "time": 1350044500}]
the get_curl function is working fine when I hardcode my $id.
I guess something is wrong with my $myString, unfortunately the $_POST cvariable is not populated, Any idea what I am missing ?
Looking at the example JSON response included in your question, I can conclude that the object you are trying to talk with is wrapped in an array (hence the [ and ] around it in the JSON string).
You should access it using $answers[0]->object_id.
If that doesn't work, you can always use var_dump to check out the data in one of your variables.

Codeigniter query does not insert

The data is being sent from the front end like this:
var data = {
'user_id':userid,
'qid':array[qnum].qid,
'user_ans':userAnswers[qnum].answer,
'user_time':userTime,
'exerciseid':exid,
'point_scored':points
};
$.post('<?php echo base_url()?>main/update_user_score',
{ myData : data },
function(result){} );
And in my "main" controller, I have:
$post_data = $_POST['myData'];
$data = array(
'user_id' => $post_data[user_id] ,
'qid' => $post_data[qid],
'user_ans' => $post_data[user_ans],
'user_time' => $post_data[user_time],
'exerciseid' => $post_data[exerciseid],
'point_scored' => $post_data[point_scored]
);
$this->load->model('Question_model','questions');
$this->questions->update_user_attempt($data);
In my Question_model / update_user_attempt:
error_log("data in model BEFORE INSERT:" . json_encode($data));
$this->db->insert('user_attempt', $data);
error_log("data in model AFTER INSERT: ");
The problem is, the data reaches (at least seems to me) the model quite fine. Here's the log entry:
[23-Apr-2012 16:04:47] data in model BEFORE INSERT:{"user_id":"5","qid":"3","user_ans":"d","user_time":"3","exerciseid":"cr1","point_scored":"35"}
BUT there is NO "after insert" log entry. The insert itself does not happen, and neither does the log entry after the insert.
I can read from the DB quite fine. So I checked in phpmyadmin the user privileges of the user in "config/database.php", and that user has ALL privileges, including INSERT.
So two questions:
What is the problem? What mistake am I making?
How do I even begin finding out what is going on with the insert statement? (I cannot find anything in the logs.)
I am looking at xampp/apache/logs/error.log and xampp/php/logs/php_error_log. Should I be looking at some other logs?
Try putting $this->db->_error_message(); after db insert
like this ...
error_log("data in model BEFORE INSERT:" . json_encode($data));
$this->db->insert('user_attempt', $data);
echo $this->db->_error_message();
error_log("data in model AFTER INSERT: ");
Aren't you missing this
$post_data['user_id']
Instead you are using without quotes
Don't forget to use $this->db->last_query() after your insert statement to see what the insert statement looks like. copy and paste that insert statement into your sql client to see if the query is actually working on its own.
Try adding
ini_set("display_errors", "1");
Also before your insert,
var_dump($data); die();
to see exactly what you are passing. Then check here to see that you are properly forming the insert statment.
First thing I thought was: shouldn't you use json_decode in stead of json_encode?
Did you set error_reporting(E_ALL);?

Extract Data from a Website using PHP

I am trying to get PHP to extract the TOKEN (the uppercase one), USERID (uppercase), and the USER NAME (uppercase) from a web page with the following text.
{
"rsp":{
"stat":"ok",
"auth":{
"token":"**TOKEN**",
"perms":"read",
"user":{
"id":"**USERID**",
"username":"**USER NAME**",
"fullname":"**NAME OF USER**"
}
}
}
}
(This is from the RTM api, getting the authentication token of the user).
How would I go about doing this? Thanks!
EDIT:
how would i get task name "Buy Milk!" & the due date of the task"2011-02-28T.." using json_decode and php here? Thanks!
{
"rsp":{
"stat":"ok",
"tasks":{
"rev":"REV_NUMBER",
"list":{
"id":"ID_NUMBER",
"taskse­­ries":{
"id":"ID_NUMBER",
"created":"2010-11-16T00:01:50Z",
"modified":"2011-02-28T05:09:36Z",
"name":"Buy Milk!",
"source":"js",
"url":"",
"location_id":"",
"rrule":{
"every":"1",
"$t":"FREQ=W­­EEKLY;INTERVAL=1"
},
"tags":[
],
"participants":[
],
"notes":[
],
"task":{
"id":"ID_NUMBER" ­­,
"due":"2011-02-28T05:00:00Z",
"has_due_time":"0",
"added":"2011-02-21T05:04:49Z",
"completed":"",
"deleted":"",
"priority":"2",
"postponed":"0",
"estima­­te":""
}
}
}
}
}
}
As Delan suggested, use json_decode. Here is an example of how you would use json_decode to extract the information you require.
// your json string
$string = '{"rsp":{"stat":"ok","auth":{"token":"**TOKEN**","perms":"read","user":{"id":"**USERID**","username":"**USER NAME**","fullname":"**NAME OF USER**"}}}}';
// parse json string to an array
$array = json_decode($string, true);
// auth token
echo $array['rsp']['auth']['token'];
// user details
echo $array['rsp']['auth']['user']['id'];
echo $array['rsp']['auth']['user']['username'];
echo $array['rsp']['auth']['user']['fullname'];
UPDATE I've updated the code to use json_decode's $assoc parameter to convert from an object to an assoc array.
ANOTHER UPDATE To answer your updated question..
how would i get task name "Buy Milk!" & the due date of the task"2011-02-28T.." using json_decode and php here? Thanks!
This code would work to get the values that you want.
//string(9) "Buy Milk!"
echo $array['rsp']['tasks']['list']['taskseries']['name'];
// string(20) "2011-02-28T05:00:00Z"
echo $array['rsp']['tasks']['list']['taskseries']['task']['due'];
This code isn't ideal, but it gets the job done for you.
If the string is JSON, json_decode in PHP will do the trick. It's was implemented in PHP 5.2.0.
http://www.php.net/manual/en/function.json-decode.php

Categories