I'm trying to put a script together that will do some math for the user.
That works fine however when i try to put it in a session and try to show the value to the user it will only return 0 if its set to 0.
Does anybody know where i did wrong?
<?php
session_start();
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
$class1 = filter_var($_POST['class1'], FILTER_SANITIZE_STRING);
$class2 = filter_var($_POST['class2'], FILTER_SANITIZE_STRING);
$class3 = filter_var($_POST['class3'], FILTER_SANITIZE_STRING);
$class4 = filter_var($_POST['class4'], FILTER_SANITIZE_STRING);
$class5 = filter_var($_POST['class5'], FILTER_SANITIZE_STRING);
$class1C = $class1 * 35;
$class2C = $class2 * 5;
$class3C = $class3 * 7.5;
$class4C = $class4 * 26;
$class5C = $class5 * 2.5;
$totaal1 = $class1C + $class2C + $class3C + $class4C + $class5C;
$res = array($class1C, $class2C, $class3C, $class4C, $class5C, $totaal1);
foreach($res as $name => $var) {
$_SESSION[$name] = $var;
}
$result = array("error" => false, "html" => null);
$result["error"] = false;
$result["html"] = "<h3>Session information: var_dump($_SESSION[$class1C]) ($_SESSION[$class2C]) ($_SESSION[$totaal1])</h3>";
} else {
$result["error"] = true;
$result["html"] = "<h3>Error</h3>";
}
echo json_encode($result);
exit;
?>
You cannot call var_dump inside the double quoted string, and var_dump does not return anything: it only display things.
Even if you could, $class1C is not a valid index for $_SESSION
Keeping the same logic as your code, you may change your line to the following:
$result["html"] = "<h3>Session information:";
ob_start();
var_dump($_SESSION[0]); // contains $class1C
echo $_SESSION[1]; // contains $class2C
echo $_SESSION[5]; // contains $totaal1
$result["html"] .= ob_get_clean();
$result["html"] .= "</h3>";
EDIT:
If you want to use the indexes 'class2C', 'totaal1' etc.. you need to init $res as follow:
$res = array(
'class1C' => $class1C,
'class2C' => $class2C,
'class3C' => $class3C,
'class4C' => $class4C,
'class5C' => $class5C,
'totaal1' => $totaal1
);
Then, your loop to set $_SESSION will set correct indexes, and you will be able to use $_SESSION['class1C'] to get proper values.
Related
I want to fetch all products from Square Catalog.
Here is the code:
require 'vendor/autoload.php';
use Square\SquareClient;
use Square\LocationsApi;
use Square\Exceptions\ApiException;
use Square\Http\ApiResponse;
use Square\Models\ListLocationsResponse;
use Square\Environment;
$client = new SquareClient([
'accessToken' => '{{access_token}}',
'environment' => Environment::SANDBOX,
]);
//Providing SKU
$object_ids = ['GFLR20L', '232GGGD'];
$body = new \Square\Models\BatchRetrieveCatalogObjectsRequest($object_ids);
$body->setIncludeRelatedObjects(true);
$api_response = $client->getCatalogApi()->batchRetrieveCatalogObjects($body);
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
} else {
$errors = $api_response->getErrors();
}
Output:
object(Square\Models\BatchRetrieveCatalogObjectsResponse)#13 (3)
{
["errors":"Square\Models\BatchRetrieveCatalogObjectsResponse":private] => NULL
["objects":"Square\Models\BatchRetrieveCatalogObjectsResponse":private] => NULL
["relatedObjects":"Square\Models\BatchRetrieveCatalogObjectsResponse":private] => NULL
}
**> Post Suggestions by sjosey:
My PHP Code:
Looking for Products with name Paper in it.**
$object_types = ['ITEM'];
$prefix_query = new \Square\Models\CatalogQueryPrefix('name', 'paper');
$query = new \Square\Models\CatalogQuery();
$query->setPrefixQuery($prefix_query);
> Storing Values Here
$body = new \Square\Models\SearchCatalogObjectsRequest();
$body->setObjectTypes($object_types);
$body->setQuery($query);
$body->setLimit(100);
$api_response = $client->getCatalogApi()->searchCatalogObjects($body);
> Fetching the api response here
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
} else {
$errors = $api_response->getErrors();
}
> Echo Result
var_dump($result);
Here is the output:
object(Square\Models\SearchCatalogObjectsResponse)#15 (5) { ["errors":"Square\Models\SearchCatalogObjectsResponse":private]=> NULL ["cursor":"Square\Models\SearchCatalogObjectsResponse":private]=> NULL ["objects":"Square\Models\SearchCatalogObjectsResponse":private]=> NULL ["relatedObjects":"Square\Models\SearchCatalogObjectsResponse":private]=> NULL ["latestTime":"Square\Models\SearchCatalogObjectsResponse":private]=> string(20) "1776-07-04T00:00:00Z" }
object_ids are not the same as SKU; they are unique generated ids on Square's side. You would want to use the SearchCatalogObjects (POST /v2/catalog/search) endpoint instead to search by SKU. An example query using one of your SKUs would be:
{
"query": {
"exact_query": {
"attribute_name": "sku",
"attribute_value": "GFLR20L"
}
}
}
This will get your catalog object ids, but if you're interested in the inventory you would still need to use another endpoint to get the inventory, such as RetrieveInventoryCount (which takes the catalog_object_id's as the parameter).
Figured out the solution. The following codes fetches a list of all the products by Product IDS. The array can be used to set data as per requirements (By SKU or Anything)
require 'vendor/autoload.php';
use Square\SquareClient;
use Square\LocationsApi;
use Square\Exceptions\ApiException;
use Square\Http\ApiResponse;
use Square\Models\ListLocationsResponse;
use Square\Environment;
$client = new SquareClient([
'accessToken' => '{{access_token}}',
'environment' => Environment::PRODUCTION,
]);
$bag = [];
$cursor = null;
$ctr = 1;
$api_response = $client->getCatalogApi()->listCatalog($cursor, 'ITEM');
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
} else {
$errors = $api_response->getErrors();
}
$g1 = $result;
$g2 = json_encode($g1);
$g3 = json_decode($g2);
$cursor = $g3->cursor;
$objects = $g3->objects;
$g4 = json_encode($objects);
$g5 = json_decode($g4);
foreach($g5 as $g51){
$bag[$g51->id] = $g51;
}
while($cursor != null){
$api_response2 = $client->getCatalogApi()->listCatalog($cursor, 'ITEM');
if ($api_response2->isSuccess()) {
$result2 = $api_response2->getResult();
} else {
$errors2 = $api_response2->getErrors();
}
$g6 = $result2;
$g7 = json_encode($g6);
$g8 = json_decode($g7);
$cursor = $g8->cursor;
$objects2 = $g8->objects;
$g9 = json_encode($objects2);
$g10 = json_decode($g9);
foreach($g10 as $g101){
$bag[$g101->id] = $g101;
}
}
var_dump(count($bag));
Partly confused (still) because the variable $investment_type resulting of "Creating default object from empty value" when I follow this previous question of mine Laravel list() with each() function error with deprecated function.
This is the original code.
$assetsData = ClientPropertyManagement::find($assets_id);
$investmentType = Input::get('investmenttype'.$assets_id);
$legalname = Input::get('legalname'.$assets_id);
$ownership = Input::get('ownership'.$assets_id);
$tic = Input::get('tic'.$assets_id);
$entity_id = Input::get('entity_id'.$assets_id);
foreach($investmentType as $investment_type) {
list($key,$value) = each($legalname);
list($key,$valueOwner) = each($ownership);
list($key,$valueTic) = each($tic);
list($key,$valueEntityId) = each($entity_id);
if($valueEntityId == 0) {
$assetEntity = new ClientEntityManagement;
$assetEntity->property_id = $assetsData->property_id;
$assetEntity->client_id = $id;
} else {
$assetEntity = ClientEntityManagement::find($valueEntityId);
}
$assetEntity->investment_type = $investment_type;
$assetEntity->entity_name = $value;
$assetEntity->ownership = $valueOwner;
$assetEntity->ticnum = $valueTic;
$assetEntity->save();
}
Here's what I did in my code.
foreach( $investmentType as $key => $investment_type ) {
$assetEntity->investment_type = $investment_type;
$assetEntity->entity_name = $legalname[$key];
$assetEntity->ownership = $ownership[$key];
$assetEntity->ticnum = $tic[$key];
if ( $entity_id[$key] == 0 ) {
$assetEntity = new ClientEntityManagement;
$assetEntity->property_id = $assetsData->property_id;
$assetEntity->client_id = $id;
} else {
$assetEntity = ClientEntityManagement::find($investment_type);
}
$assetEntity->save();
}
The problem is that $assetEntity isn't created yet, and you are trying to use as an object. To solve that, you need to change the position where you instantiate the object and create the variable $assetEntity:
foreach( $investmentType as $key => $investment_type ) {
if ( $entity_id[$key] == 0 ) {
$assetEntity = new ClientEntityManagement;
$assetEntity->property_id = $assetsData->property_id;
$assetEntity->client_id = $id;
} else {
$assetEntity = ClientEntityManagement::find($investment_type);
}
$assetEntity->investment_type = $investment_type;
$assetEntity->entity_name = $legalname[$key];
$assetEntity->ownership = $ownership[$key];
$assetEntity->ticnum = $tic[$key];
$assetEntity->save();
}
That way $assetEntity will be created, and then you populate the other attributes.
Also, you may want to use the IoC Container and replace the new ClientEntityManagement with App::make('ClientEntityManagement'). Read more at https://laravel.com/docs/4.2/ioc
I am working on a JSON file in which I want to increment instead of overwriting the data. However I cannot seem to do this (since it keeps on overwriting instead of adding data with an incremented ID).
The code underneath is: database_json.php (as u can see I include it in saveJson.php)
$databaseFile = file_get_contents('json_files/database.json');
$databaseJson = json_decode($databaseFile, true);
$database = $databaseJson['data'];
the below is the code of the file saveJson.php contains the following code:
// below starts a new page, the page that submits the form called saveJson.php
include_once('database_json.php');
$data = $_POST;
//Setup an empty array.
$errors = array();
if (isset($data)) {
$newExerciseData = $data;
$exerciseArray = $data['main_object'];
$databaseFile = 'json_files/database.json';
$textContent = file_get_contents($databaseFile);
$database = json_decode($textContent, true);
if ($data['id'] === 'new') {
if (count($database['data']) == 0) {
$ID = 0;
}
else {
$maxID = max($database['data']);
$ID = ++$maxID["id"];
}
$newJsonFile = 'jsonData_' . $ID . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData = array(
'id' => $ID,
// a lot of variables that aren't related to the problem
);
$database['data'][] = $newArrayData;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
}
else {
$index = array_search((int) $_POST['id'], array_column($database['data'], 'id'));
$correctJsonFile = 'json_files/jsonData_' . $_POST['id'] . '.json';
$newJsonFile = 'jsonData_' . $_POST['id'] . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData2 = array(
'id' => (int) $_POST['id'],
// more not related to problem variables
);
$database['data'][$index] = $newArrayData2;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE));
}
echo json_encode($newExerciseData, JSON_UNESCAPED_UNICODE);
}
so, what I wish for: To increment the IDs and NOT to overwrite the data.
I already did some research and didn't find any useful information besides this --> Auto increment id JSON, but to me it looks like I have the same principle applied.
I am trying to display all records using jason in php.
but display all filed with null value.
I'm using postman for testing purpose.
I don't know what is the problem with that code. I getting null value only.
here is my code :
<?php
header('Content-Type: application/json');
$checkFields = "";
$REQUEST = $_SERVER['REQUEST_METHOD'];
if ($REQUEST == "POST")
{
include "DB/db.php";
$userlist = mysql_query("SELECT * FROM reg_services");
if(mysql_num_rows($userlist) > 0)
{
$p = 0;
$ph = array();
while($userlistdata = mysql_fetch_row($userlist))
{
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
$json = array("success" => 1, "All_User_List" => $ph);
$jsonarray = json_encode($json);
}
}
else
{
$json = array("success" => 0, "message" => "Invalid Request Type(Use POST Method)");
$jsonarray = json_encode($json);
}
echo $jsonarray;
?>
please help me if you are know what is the error in code.
just replace this code with old one
$p = 0;
$ph = array();
while($userlistdata = mysql_fetch_array($userlist))
{
$ph[$p] = array();
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
You need to tell PHP about arrays
while($userlistdata = mysql_fetch_row($userlist))
{
$ph[$p] = array(); // let PHP know it is an array
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
just replace this while loop condition with olde one.
while($userlistdata = mysql_fetch_array($userlist))
now it's work
I have an array containing several variables from my sql database.
{"gold":"0","silver":"0","bronze":"0","gdp":"12959563902","population":"3205000","country_name":"Albania"}, {"gold":"1","silver":"0","bronze":"0","gdp":"188681000000","population":"35468000","country_name":"Algeria"}
I have an additional variable called $score that uses information from the database to calculate this score. I want to know how I can loop through and add the correct score to each country in the array.
My Original Code:
$row = $res->fetchRow();
$resGold = $row['gold'];
$resSilver = $row['silver'];
$resBronze = $row['bronze'];
$resGdp = $row['gdp'];
$resPopulation = $row['population'];
$resCountry = $row['country_name'];
$gold_score = ($resGold * $gold_value);
$silver_score = ($resSilver * $silver_value);
$bronze_score = ($resBronze * $bronze_value);
if($population == true){
$score = (($gold_score + $silver_score + $bronze_score)/$resPopulation);
}
else if($gdp == true){
$score = (($gold_score + $silver_score + $bronze_score)/$resGdp);
}
$result = $res->fetchAll();
$result[] = array('score' => $score);
echo json_encode($result);
Your code will be something like this:
$json_data = '{"gold":"0","silver":"0","bronze":"0","gdp":"12959563902","population":"3205000","country_name":"Albania"},
{"gold":"1","silver":"0","bronze":"0","gdp":"188681000000","population":"35468000","country_name":"Algeria"}';
$countries_info_new = array();
$countries_info = json_decode($json_data);
foreach($countries_info as $country_info){
$country_info['score'] = Get_country_score($country_info['country_name']);
$countries_info_new[]=$country_info;
}
$new_json_data = json_encode($countries_info_new);