Posting child objects to a database with php - php

I am trying to post child objects to a database with php and can't figure this out, any help is appreciated. The top clientId to invAmount posts fine, but the invoiceDetails child objects is where I am getting confused, I tried a while loop but no luck, I am a ui guy not php so I'm out of ideas.
The post:
{
"clientId": "5",
"invNumber": "2",
"invProject": "Test Project",
"invDescription": "Test",
"invDate": "09/20/2013",
"invAmount": "5000",
"invoiceDetails": [
{
"invRowDescription": "Description 1",
"invRowHours": "50",
"invRowRate": "50",
"invRowTotal": 2500
},
{
"invRowDescription": "Description 2",
"invRowHours": "50",
"invRowRate": "50",
"invRowTotal": 2500
}
]
}
The php controller
<?php
$_POST = json_decode(file_get_contents('php://input'), true);
// Independent configuration
require 'medoo.php';
$database = new medoo(array(
// required
'database_type' => 'mysql',
'database_name' => 'dbname',
'server' => 'server',
'username' => 'user',
'password' => 'pw'
));
$database->insert("invoiceSummary", array(
"clientId" => $_POST['clientId'],
"number" => $_POST['invNumber'],
"project" => $_POST['invProject'],
"description" => $_POST['invDescription'],
"date" => $_POST['invDate'],
"amount" => $_POST['invAmount']
));
while($rowInv = mysqli_fetch_array($_POST['invoiceDetails'])) {
$database->insert("invoiceDetails", array(
"clientId" => $_POST['clientId'],
"number" => $_POST['invNumber'],
"description" => $_POST['invRowDescription'],
"hours" => $_POST['invRowHours'],
"rate" => $_POST['invRowRate'],
"total" => $_POST['invRowTotal'],
));
}
echo json_encode('success');
?>

Related

Issue saving card for customer

I would like to store credit card information for a customer in our QuickBooks account
using the PHP Payments SDK - the following is what I am trying to achieve this but I get an invalid arguments error:
$client = new PaymentClient([
'access_token' => $accessTokenValue,
'environment' => "sandbox" ]);
$array = [
"number" => "4408041234567893",
"expMonth" => "12",
"expYear" => "2026",
"name" => "Test User",
"address" => [
"streetAddress" => "1245 Hana Rd",
"city" => "Richmond",
"region" => "VA",
"country" => "US",
"postalCode" => "44112"
],
"customerid" => "94"
];
$create = CardOperations::createCard($array);
$response = $client->charge($create);
I have not had any luck reaching out to support, any way this can be done, I appreciate the help.
Error received:
Uncaught TypeError: Argument 1 passed to
QuickBooksOnline\Payments\Operations\CardOperations::createCard() must
be an instance of QuickBooksOnline\Payments\Modules\Card, array given
UPDATE using recommended code:
Uncaught ArgumentCountError: Too few arguments to function
QuickBooksOnline\Payments\Operations\CardOperations::createCard(), 1
passed
As per your error it seems the required Card data should be an instance of the class
QuickBooksOnline\Payments\Modules\Card
But you're passing array to it. As per the documentation could you please check this below code , hopefully it will work.
$client = new PaymentClient([
'access_token' => $accessTokenValue,
'environment' => "sandbox"
]);
$cardData = [
"number" => "4408041234567893",
"expMonth" => "12",
"expYear" => "2026",
"name" => "Test User",
"address" => [
"streetAddress" => "1245 Hana Rd",
"city" => "Richmond",
"region" => "VA",
"country" => "US",
"postalCode" => "44112"
],
"customerid" => "94"
];
$chargeData = [
"amount" => "10.55",
"currency" => "USD",
"card" => $cardData,
"context" => [
"mobile" => "false",
"isEcommerce" => "true"
]
];
$customerId = "94";
$charge = ChargeOperations::buildFrom($chargeData);
$chargeResponse = $client->charge($charge);
$clientId = rand();
$card = CardOperations::buildFrom($cardData);
$createCardresponse = $client->createCard($card, $clientId, rand() . "abd");
//or alternatively $createCardresponse = $client->createCard($card, $customerId, rand() . "abd");

How to use Google Cloud Healthcare API HttpBody class?

I'm having a hard time using a method setData() of the HttpBody class. I'm passing the parameter to the method as an object, but I recieve an error message.
How do I pass the parameter:
public function create(string $resource, $body)
{
$client = $this->googleClient();
$service = new CloudHealthcare($client);
$parent = "projects/my_project_id/locations/my_location/datasets/my_dataset/fhirStores/repository";
$httpBody = new HttpBody();
$httpBody->setContentType('application/fhir+json;charset=utf-8');
$httpBody->setData([
"resourceType" => "Patient",
"id" => "23434",
"meta" => [
"versionId" => "12",
"lastUpdated" => "2014-08-18T15:43:30Z"
],
"text" => [
"status" => "generated",
"div" => "<!-- Snipped for Brevity -->"
],
"extension" => [
[
"url" => "http://example.org/consent#trials",
"valueCode" => "renal"
]
],
"identifier" => [
[
"use" => "usual",
"label" => "MRN",
"system" => "http://www.goodhealth.org/identifiers/mrn",
"value" => "123456"
]
],
"name" => [
[
"family" => [
"Levin"
],
"given" => [
"Henry"
],
"suffix" => [
"The 7th"
]
]
],
"gender" => [
"text" => "Male"
],
"birthDate" => "1932-09-24",
"active" => true
]);
$data = $service->projects_locations_datasets_fhirStores_fhir->create($parent, $resource, $httpBody);
return $data;
}
Following the error message I get.
The error says I didn't pass the resourceType field, but it was passed:
Google\Service\Exception: {
"issue": [
{
"code": "structure",
"details": {
"text": "unparseable_resource"
},
"diagnostics": "missing required field \"resourceType\"",
"expression": [
""
],
"severity": "error"
}
],
"resourceType": "OperationOutcome"
} in file /usr/share/nginx/vendor/google/apiclient/src/Http/REST.php on line 128
How should I pass the parameter to receive the success message?
Tkanks!
I haven't tried the PHP client libraries specifically, but for most languages you don't want to use the HttpBody class - it's an indication that the method accepts something in the body of the request that is just text from the perspective of the method signature. I would try passing the JSON string directly.

How to create this JSON in PHP?

Sorry for the bad title, but I don't know how to create following JSON in PHP:
{
"id":"1",
"method":"getData",
"params":{
"options":{
"element":{
"id":"1a_ext",
"type":1,
"keyType":"externalkey"
},
"moreInfo":true,
"userFields":[
"id",
"name",
"longname",
"externalkey"
]
}
},
"jsonrpc":"2.0"
}
I don't know to do the part after "params" (how do I "put" options "into" params) - for the other parts I know what I have to do:
public static function getData(){
$json = array(
"id" => self::id(),
"method" => "getData",
"params" => array(
"id" => self::$userid,
"type" => self::$type
),
"jsonrpc" => "2.0"
);
$json = json_encode($json, true);
return self::request($json);
}
I would really appreciate your help, thanks!
You directly can assign to the params keys like
$json['params']['options'] = $your_options;
Full version of your code as an example
public static function getData(){
$json = array(
"id" => self::id(),
"method" => "getData",
"params" => array(
"id" => self::$userid,
"type" => self::$type
),
"jsonrpc" => "2.0"
);
# add something to param index
$json['params']['options'] = $your_options;
$json = json_encode($json, true);
return self::request($json);
}
You can create the this in array format in PHP and then JSON encode:
$arr = [
'id' => 1,
'method' => 'getData',
'params' => [
'options' => [
'element' => [
'id' => '1a_ext',
'type' => 1,
'keyType' => 'externalKey'
],
'moreInfo' => true,
'userFields' => [
'id',
'name',
'longname',
'externalKey'
]
]
],
'jsonrpc' => '2.0'
];
$json = json_encode($arr);
Instead of spoonfeeding, i would like to help related, Whenever if you find difficulties to create an array representation of a JSON then you should use var_export(array, true) the second parameter must be true to return the variable representation instead of outputting it
<?php
$json_str = '{
"id": "1",
"method": "getData",
"params": {
"options": {
"element": {"id": "1a_ext", "type": 1, "keyType": "externalkey"},
"moreInfo": true,
"userFields": ["id", "name", "longname", "externalkey"]
}
},
"jsonrpc": "2.0"
}';
$json_arr = var_export(json_decode($json_str, true), true);
print_r($json_arr);
check the output here https://paiza.io/projects/eUZZDsTsSFSM4m9WMl05Ow
$json_arr is an array representation for your JSON, now you can dynamic the array values

How to properly format sql json as desired

Basically,I want to fetch data from mysql and format it into json like this:
[
[
"title" => "first",
"uploader" => "root"
],
[
"title" => "first",
"uploader" => "root"
],
[
"title" => "first",
"uploader" => "root"
],
[
"title" => "first",
"uploader" => "root"
],
[
"title" => "first",
"uploader" => "root"
],
[
"title" => "first",
"uploader" => "root"
],
[
"title" => "first",
"uploader" => "root"
],
[
"title" => "first",
"uploader" => "root"
],
[
"title" => "first",
"uploader" => "root"
],
[
"title" => "first",
"uploader" => "root"
],
]
I used this code:
<?php
require 'config.php';
$query = $_GET['q'];
if ($query==null) {
exit('No query');
}
$sql = "SELECT title,uploader FROM `uploads_public` WHERE Title =:query ";
if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":query", $query, PDO::PARAM_STR);
// Attempt to execute the prepared statement
if($stmt->execute()){
echo "Your search $query has the following results(normal json):<br>";
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json).'<br>';
echo "While it has the following results when replaced<br>";
echo str_replace('}',']',str_replace(':','=>',str_replace('{', '[', "$json")));
} else{
echo "Something went wrong. Please try again later. <br>"; print_r($stmt->errorInfo());
}
// Close statement
unset($stmt);
unset($pdo);
}
else{
echo "No input";
}
But rather than what I wanted(mentioned above),i got this:
[["title"=>"first","uploader"=>"root"],["title"=>"first","uploader"=>"root"],["title"=>"first","uploader"=>"root"],["title"=>"first","uploader"=>"root"],["title"=>"first","uploader"=>"root"],["title"=>"first","uploader"=>"root"],["title"=>"first","uploader"=>"root"],["title"=>"first","uploader"=>"root"],["title"=>"first","uploader"=>"root"]]
It looks ok,but the major problem is that I don't want all the results compressed together ,I want it exactly the way mentioned..with line breaks(new lines) after every ..[,", and so on
Thanks

Telegram Inline Bot shows nothing inline

i am trying to create an inline bot for telegram with php. I have followed the steps with the BotFather. I have created the bot, taken the token, setinline and set the placeholder message. I have set the webhook and it's working. But when i type the bot in the message i do get nothing and if I send the message, just nothing happen. The webhook is working, I have tried it with normal messages.
This is my code, after a while I just give up and get it from a blog, edited it a bit.
$content = file_get_contents("php://input");
$update = json_decode($content, true);
$chatID = $update["message"]["chat"]["id"];
//sendMessage(print_r($update,true), $chatID);
if (isset($update["inline_query"])) {
$inlineQuery = $update["inline_query"];
$queryId = $inlineQuery["id"];
$queryText = $inlineQuery["query"];
if (isset($queryText) && $queryText !== "") {
apiRequestJson("answerInlineQuery", [
"inline_query_id" => $queryId,
"results" => ($queryText),
"cache_time" => 86400,
]);
}
else {
apiRequestJson("answerInlineQuery", [
"inline_query_id" => $queryId,
"results" => [
[
"type" => "article",
"id" => "0",
"title" => "TEST",
"message_text" => "TEST",
],
]
]);
}
}
The bot still show me nothing.
I think i just skipped a step.
The results need to have the key message_text inside the input_message_content.Therefore a result could look like this:
$results = array(
array(
"type" => "article",
"id" => "1",
"title" => "Title",
"description" => "Description",
"input_message_content" => array(
"message_text" => "<code>Message 1</code>",
"parse_mode" => "HTML"
)
)
);
$postData = array(
"inline_query_id" => $inlineQuery["id"],
"results" => json_encode($results),
"cache_time" => 0
);

Categories