How do you convert Laravel query results to json? - php

I have a query that I call with:
$query = "select * from myTable";
$results = DB::connection('myDB')->select($query);
I want to be able to get this in the simple json format of:
[{firstColumn: firstColumnValue, secondColumn: secondColumnValue},
{firstColumn: firstColumnValue, secondColumn: secondColumnValue}]
What is the easiest way to achieve this?

As I have read here : Laravel, converting data from raw query to JSON
you can just use the json_encode. Hope that one helps.

If you thought of writing web service or something related to it, then
$Response = array('success' => '1', 'result' => $yourData);
else
$Response = array('success' => '0', 'error' => 'Your Custom Errors');
return json_encode($Response);
So that you can handle it in while you retrieve according to the result.

Related

Sending a php array as a dialogflow response

Hey I am building a chatbot using dialogflow and I am generating the responses by using a customized Webhook (I am programming in php). I am extracting data from my database and storing it in an array but when I send the array as a response to dialogflow it only shows the first row.
Here is my code:
<?php
header('Content-Type: text/html; charset=utf-8');
date_default_timezone_set("Asia/Bangkok");
$date = date("Y-m-d");
$time = date("H:i:s");
$json = file_get_contents('php://input');
$request = json_decode($json, true);
$input = fopen("log_json.txt", "w") or die("Unable to open file!");
fwrite($input,$json);
fclose($input);
function processMessage($update) {
if($update["queryResult"]["action"] == "ques"){
$bdd= new PDO('mysql:host=localhost;dbname=****', '****', '***', array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")) ;
$data = array();
$nom= $update["queryResult"]["parameters"]["nom_aliment"];
$info=$update["queryResult"]["parameters"]["Information"];
$quantite=$update["queryResult"]["parameters"]["Quantite"];
$req=$bdd->prepare("SELECT * FROM TableCiqual WHERE alim_nom LIKE ? ");
$req->execute(array("%$nom%"));
while($resultat=$req->fetch()){
$variab=$resultat[$info]*$quantite/100;
$ppp =$resultat['alim_nom'].' '.$info.' : '.$variab;
$data=$ppp;
}
sendMessage(array(
"source" => $update["responseId"],
"fulfillmentText"=>$data,
"payload" => array(
"items"=>[
array(
"simpleResponse"=>
array(
"textToSpeech"=>"Bad request"
)
)
],
),
));
}
}
function sendMessage($parameters) {
echo json_encode($parameters);
}
I know that my query returns multiple results all these results are stored in the array $data that I send as a response in dialogflow. The problem is that dialogflow only shows me the first row of the array $data instead of the whole array with all the rows.
My question is : Is it possible to send an array as a response in dialogflow and if yes how so.
I think there are two issues here.
The first is that $data is not actually containing a list of your results. The line
$data = $ppp;
is assigning $ppp, which is a string, to $data rather than adding on to the end of the array. I think, for that line, you want something more like
$data[] = $ppp;
However, this doesn't solve your problem completely, since the fulfillmentText attribute in JSON isn't expecting an array - it is expecting a string. So you probably want to concatenate all of those entries with something like
"filfillmentText" => implode( "\n", $data );
However, this assumes that you both want a new line in between each answer and that the chat system you're using supports the feature this way - not all do. (And you haven't indicated which one you're using.)

Returning an array from PHP to jQuery from Ajax

I'm trying to get PHP returned array from Ajax.
Here is my Ajax call:
And my PHP code is this:
Query is running perfectly.
I have tried to get values like alert(data[0].program_title) in ajax success. But it also returns Undefined.
How can I fix this issue?
In your PHP code:
//remove
return $data
//change with
echo json_encode($data);
Just before flushing the data back to the stream (returning), convert your data ($data variable in this case) to JSON string using json_encode and add the proper content-type application/json using header function.
However, the best practice is to provide some metadata to your data included in your transfer, like the size of data and count of elements in data and if paginated, which page the data refers to and what the maximum available pages and maximum element size of a page are.
Here's a sample body structure for a more robust data transfer:
$response = [
'page' => 0, // e.g.
'count' => count($data),
'data' => $data,
'max_page' => 3, // e.g.
'item_per_page' => 15, // e.g.
'status_code' => 200, // e.g.
];
header ( "Content-Type: application\/json", true , 200);
return json_encode(
$response
, JSON_INVALID_UTF8_SUBSTITUTE
| JSON_NUMERIC_CHECK
| JSON_PRESERVE_ZERO_FRACTION
| JSON_UNESCAPED_LINE_TERMINATORS
| JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE
);
Try this:
$data = [];
if ($numRows>0) {
while($row=$result->fetch_assoc()) {
$data[] = $row;
}
}
Replace return with echo and add json_encode
echo json_encode($data);

need help in PHP soap

i try to fetch result from www.tadawul.com.sa with php soap client.
but when i try to load that , get nothing just loading page.
here is my code.
$reference = array(
'companyId' => '*********',
'secureKey' => '*********'
);
$client = new SoapClient('http://www.tadawul.com.sa/Tadawul_WebAPI/services/GetDetailQuote?wsdl');
$response = $client->getDetailQuoteForCompany($reference);
var_dump($response);
I think the problem is in the structure you need to pass a getDetailQuoteForCompanyRequest Object not an array
Why don't you use wsdl2phpgenerator
It'll make you life easier, You need to pass wsdl file and it will generate all the classes that you need
Instead of this
$response = $client->getDetailQuoteForCompany($reference);
Try
$response = $client->__soapCall("getDetailQuoteForCompany", array($reference));

How to append new element in JSON file without get all data of this file in PHP

i need to append some elements to json file
this is my code:
routes.php (stage1)
$array = ['id' => '1', 'number' => '123123', 'name' => 'ahmed'];
$json_array = json_encode($array);
Storage::append('test.json', json_encode(['user_name' => 'ahmedsk']));
test.json
{"user_name":"ahmedsk"}
{"id":"1","number":"24142","username":"ahmedsk"}
but when i make print_r() for $result it's not feedback
routes.php (stage2)
$result = Storage::get('test.json');
print_r($result);
With knowing i don't need to use the method of get all data from JSON file and edited it and resave it in file.
Thanks
The question is some how vague.
if you need to print the json file as an array this is what you need :
routes.php (stage2)
$result = Storage::get('test.json');
print_r(json_decode("[" . preg_replace("/\n+/",",",$result) . "]"));
test :
https://eval.in/499591

JSON PHP to JSON Python

I am converting my php over to python.
In my php I have (this has always work with my iPhone app):
...
$profile = mysql_fetch_array($query_result, MYSQL_ASSOC);
$profile_json = array();
$profile_json[] = $profile;
echo json_encode(array('success' => 1, 'myProfile' => $profile_json));
I know have this in Python (doesn't seem to work with iPhone app):
...
profile = db_cursor.fetchone()
json_user_profile = json.dumps(profile)
json_obj= {'success': 1, 'myProfile': json_user_profile,}
self.response.out.write(json.dumps(json_obj))
I need my python to return exactly what my php was returning.
Anyone up to help? :)
Pretty sure you need to change it to:
profile = db_cursor.fetchone()
json_obj= {'success': 1, 'myProfile': profile}
self.response.out.write(json.dumps(json_obj))
Otherwise you are double json encoding the profile

Categories