dynamodb getitem using php - I only want to retrieve the value - php

I'm able to query my dynamodb tables, but I only want to retrieve the actual value. I don't want the formatting output. This same question has been answered here for Java, but I'm looking for the PHP solution:
Retrieving just the item value from a dynamodb table?
Here is my getitem query:
$response = $dynamodb->getItem(array(
"TableName" => $tableName,
"ConsistentRead" => true,
"Key" => array(
"userguid" => array(Type::STRING => $userguid)
),
"AttributesToGet" => array("token")
));
print_r($response["Item"]["token"]);
Here is the output:
Array
(
[S] => 9d194513
)
All I want to get back is:
9d194513
I assumed the logical answer would be to change the last line to:
print_r($response["Item"]["token"]["S"]);
But then my code doesn't return anything at all. Obviously still learning PHP here, and any help would be appreciated.

Don't use print_r function, just either echo your variables
echo $response["Item"]["token"]["S"];
or store in a variable for later use
$res_token = $response["Item"]["token"]["S"];

You can also use the getPath convenience method built into the Model object that the SDK returns for operations.
echo $response->getPath('Item/token/S');
For more information about working with responses in the SDK, see the Response Models page in the AWS SDK for PHP User Guide.

Though it's an old question but for anyone coming to this page for seeking answer, this is how I have done it.
getItem returns a Resultobject. You can call the get() function of the SDK, which will give you an array containing the exact value.
$params = [
"TableName" => "EpgApiAccessCount",
"Key" => $this->marshalJson('
{
"ApiUserKey": "' . $apiUserkey . '"
}
')
];
$result = $this->client->getitem($params);
if (!$result instanceof ResultInterface) {
return 0;
}
$item = $this->unmarshalItem($result->get("Item"));
return $item["AccessCount"];
Of course your value and table name will be different, and you can print or do anything else with the value.

Related

Parse WHERE php

I using https://github.com/ParsePlatform/parse-php-sdk.
I want to send notify 2 other devices.
But it's only send notify for device token is 'abcdef'.
How to send notify 2 other devices?
Thanks all,
$query = ParseInstallation::query();
$query->equalTo('deviceToken', 'xxxxx');
$query->equalTo('deviceToken', 'abcdef');
$data = [
'data' => ['alert' => 'Hello, this is a test'],
'where' => $query,
];
ParsePush::send(
$data
);
I believe your dual equalTo queries are overwriting each other. From what I understand, equalTo matches a single value. You should be able to see this behavior by inspecting a vardump of your $query after each equalTo call.
You should instead use containedIn (http://parseplatform.github.io/parse-php-sdk/classes/Parse.ParseQuery.html#method_containedIn) and pass in an array of values that you'd like the query to match. E.g., $query->containedIn('deviceToken', ['abcdef', 'xxxxx']).
Note: I don't have a parse PHP project handy so the above code isn't tested, but the general logic should work.

Modx xPDO getMany not returning expected results

I'm not sure what is going on here, but I'm trying to retrieve some budgets from a modx/xpdo object and getting unexpected results. From the code below, both foreach loops return the same results [that of the first getMany call. 2 items] if I switch the order of the getmany calls I get only one result for both foreach loops.
$tipa = $this->modx->getObject('Tipa', array('id' => $id, 'token' => $token));
// should retrieve two objects
$tipa_sub_budgets = $tipa->getMany('TipaBudget', array('budget_type_id:!=' => '999'));
foreach($tipa_sub_budgets as $sb){
echo $sb->get('id');
}
// should retrieve one object
$tipa_primary_budgets = $tipa->getMany('TipaBudget', array('budget_type_id' => '999'));
foreach($tipa_primary_budgets as $tb){
echo $tb->get('id');
}
I'm not sure what is happening here. What is the correct way to grab 2 sets of objects from the $tipa object?
I think whereas xPDO::getObject() can be passed the criteria either as an array or an instance of xPDOCriteria, xPDOObject::getMany() expects only an instance of xPDOCriteria meaning the array will not work.
Try passing an instance of xPDOCriteria like so...
$criteria = $this->modx->newQuery("TipdaBudget"); // classname, not the alias
$criteria->where(array("budget_type_id:!=" => 999));
$tipa_sub_budgets = $tipa->getMany("TipaBudget", $criteria);

Return Different PHP Array Values Based on A User ID-Related Constant

I am working with an array of tokens for an HTML template. Two of them ('{SYS_MENU}' and '{SUB_MENU}') are used to generate control buttons for the web application. Right now the buttons show up on the login page before the user's credential's are validated, and I need to change the code so that the buttons are hidden until after users login and reach the main menu. When someone types the http: address into their browser and arrives at the login page the system starts a session for them in the MySQL sessions table with USER_ID = 0. After they login the USER_ID changes to whatever number was assigned to them at initial registration (Example: USER_ID = 54), and after they logout at the end of the session back to 0. Tying this constant to the buttons seems like the best solution and I have found it to work in the past under similar circumstances.
Here is the original array:
$template_vars = array(
'{LANG_DIR}' => $lang_text_dir,
'{TITLE}' => theme_page_title($section),
'{CHARSET}' => $charset,
'{META}' => $meta,
'{GAL_NAME}' => $CONFIG['gallery_name'],
'{GAL_DESCRIPTION}' => $CONFIG['gallery_description'],
'{SYS_MENU}' => theme_main_menu('sys_menu'),
'{SUB_MENU}' => theme_main_menu('sub_menu'),
'{ADMIN_MENU}' => theme_admin_mode_menu(),
'{CUSTOM_HEADER}' => $custom_header,
'{JAVASCRIPT}' => theme_javascript_head(),
'{MESSAGE_BLOCK}' => theme_display_message_block(),
);
The first thing I did was to work with the references directly in the HTML template. I saw an example on w3schools that made it look like you could just type a PHP script into HTML and have it resolve. That didn't do anything except echo a bunch of text randomly into the page. I then found another citation that said you had to activate the PHP with an .HTACCESS entry before it would work directly in HTML. But that didn't close the deal either.
I know that changing '{SYS_MENU}' and '{SUB_MENU}' values in the array to => "", produces the results that I want (I.E. make the menu buttons disappear). So my next thought was I'll create an IF statement that returns two versions of the array based on circumstances, something like:
if(USER_ID != 0)
{
return $template_vars = //FIRST VERSION OF ARRAY WITH FULL VALUES//
}
else
{
return $template_vars = //SECOND VERSION OF ARRAY WITH ONLY => ""//
}
But all that did was cause the application load to terminate at a white screen with no error feedback.
My most recent attempt came from something I read here on Stack Overflow. I know that you cannot put IF statements into an array. But the article at this link described a workaround:
If statement within an array declaration ...is that possible?
So I rewrote the array as follows:
template_vars = array(
'{LANG_DIR}' => $lang_text_dir,
'{TITLE}' => theme_page_title($section),
'{CHARSET}' => $charset,
'{META}' => $meta,
'{GAL_NAME}' => $CONFIG['gallery_name'],
'{GAL_DESCRIPTION}' => $CONFIG['gallery_description'],
'{SYS_MENU}' => ('USER_ID != 0' ? theme_main_menu('sys_menu') : ""),
'{SUB_MENU}' => ('USER_ID != 0' ? theme_main_menu('sub_menu') : ""),
'{ADMIN_MENU}' => theme_admin_mode_menu(),
'{CUSTOM_HEADER}' => $custom_header,
'{JAVASCRIPT}' => theme_javascript_head(),
'{MESSAGE_BLOCK}' => theme_display_message_block(),
);
But that seems to have no effect at all. The application doesn't crash but the buttons are static whether you are logged in or logged out.
My question is: What am I missing? I can see that this is possible. But I've been trying things for a day and a half and just seem to be dancing around the solution. Your thoughts would be greatly appreciated.
The problem here is that you are calling return. With a global include file like this there is not context to return to so the application terminates. What you want to do is just assign the variables.
if(USER_ID != 0)
{
$template_vars = //FIRST VERSION OF ARRAY WITH FULL VALUES//
}
else
{
$template_vars = //SECOND VERSION OF ARRAY WITH ONLY => ""//
}

Symfony sfWidgetFormDoctrineChoice with multiple option on

I have created a form in which i embed another form. My question is about this embedded form - I'm using a sfWidgetFormDoctrineChoice widget with option multiple set to true. The code for this embedded form's configure method:
public function configure()
{
unset($this['prerequisite_id']);
$this->setWidget('prerequisite_id', new sfWidgetFormDoctrineChoice(array(
'model' => 'Stage',
'query' => Doctrine_Query::create()->select('s.id, s.name')->from('Stage s')->where('s.workflow_id = ?', $this->getOption('workflow_id') ),
'multiple' => true
)));
$this->setValidator('prerequisite_id', new sfValidatorDoctrineChoice(array(
'model' => 'Stage',
'multiple' => true,
'query' => Doctrine_Query::create()->select('s.id, s.name')->from('Stage s')->where('s.workflow_id = ?', $this->getOption('workflow_id') ),
'column' => 'id'
)));
}
I unset the prerequisite_id field because it is included in the base form, but I want it to be a multiple select.
Now, when I added the validator, everything seems to work (it passes the validation), but it seems like it has problems saving the records if there is more than one selection sent.
I get this PHP warning after submitting the form:
Warning: strlen() expects parameter 1 to be string, array given in
D:\Development\www\flow_dms\lib\vendor\symfony\lib\plugins\sfDoctrinePlugin\lib\database\sfDoctrineConnectionProfiler.class.php
on line 198
and more - I know, why - in symfony's debug mode I can see the following in the stack trace:
at Doctrine_Connection->exec('INSERT INTO stage_has_prerequisites
(prerequisite_id, stage_id) VALUES (?, ?)', array(array('12', '79'),
'103'))
So, what Symfony does is send to Doctrine an array of choices - and as I see in the debug sql query, Doctrine cannot render the query correctly.
Any ideas how to fix that? I would need to have two queries generated for two choices:
INSERT INTO stage_has_prerequisites (prerequisite_id, stage_id) VALUES (12, 103);
INSERT INTO stage_has_prerequisites (prerequisite_id, stage_id) VALUES (79, 103);
stage_id is always the same (I mean, it's set outside this form by the form in which it is embedded).
I have spend 4 hours on the problem already, so maybe someone is able to provide some help.
Well, I seem to have found a solution (albeit not the best one, I guess). Hopefully it'll be helpful to somebody.
Finally, after much thinking, I have concluded that if the problem comes from the Doctrine_Record not being able to save the record if it encounters an array instead of a single value, then the easiest solution would be to overwrite the save() method of the Doctrine_Record. And that's what I did:
class StageHasPrerequisites extends BaseStageHasPrerequisites
{
public function save(Doctrine_Connection $conn = null)
{
if( is_array( $this->getPrerequisiteId() ) )
{
foreach( $this->getPrerequisiteId() as $prerequisite_id )
{
$obj = new StageHasPrerequisites();
$obj->setPrerequisiteId( $prerequisite_id );
$obj->setStageId( $this->getStageId() );
$obj->save();
}
}
else
{
parent::save($conn);
}
}
(...)
}
So now if it encounters an array instead of a single value, it just creates a temporary object and saves it for each of this array's values.
Not an elegant solution, definitely, but it works (keep in mind that it is written for the specific structure of the data and it's just the effect of my methodology, namely See What's Wrong In The Debug Mode And Then Try To Correct It Any Way Possible).

CakePHP array() is empty, but query seems to be getting the correct results

I am trying to extract ONLY the PlanDetails where PlanDetail.company_id = Company.id AND PlanDetail.id' => $id.. ( you can see the conditions in my controller below)..
Controller:
function pd_list_by_company($id = null) {
$this->recursive = 2; // I am going to use containable to trim this.
return $this->PlanDetail->find('all',
array('conditions' =>
array('AND' =>
array('PlanDetail.company_id' => 'Company.id',
array('PlanDetail.id' => $id)))));
}
Test View:
$planDetailsByCompany = $this->requestAction('/planDetails/pd_list_by_company');
debug($planDetailsByCompany );
Output result of my debug??
Array()
If I remove the conditions and just have the find all, I get all PlanDetails as expected, so I know the data is being passed.. SQL debug dump even shows the query:
WHERE ((`PlanDetail`.`company_id` = 'Company.id') AND (`PlanDetail`.`id` IS NULL))
And yes, I did notice the $id is NULL, and I know the value needs to be there.. So maybe my question is why is the $id value not being passed to the controller even though I can see the PlanDetail.id value on a find('all') w/ out the conditions??
Thanks for any tips.
Since $id seems to be null, I would assume that you call the function without the parameter. And you don't get an error message, because as far as PHP is concerned the parameter is optional. In this case it's clearly required, so you should make it a required parameter in your function declaration:
function pd_list_by_company($id) {
Also you could simplify the return statement, you do not need the AND:
return $this->PlanDetail->find('all',
array('conditions' =>
array('PlanDetail.company_id' => 'Company.id','PlanDetail.id' => $id)
)
);
To answer the question why is the $id not being passed is because you're not passing it
To pass say $id of 2 you need to do the following in your requestAction
$this->requestAction('/planDetails/pd_list_by_company/2');
Seems to me that your code should just be
return $this->PlanDetail->find('array('PlanDetail.id' => $id));
Assuming you have the $this->PlanDetail->recursive flag set to > 0, your Model should already know about and return the associated data for any 'Company' table.....
I'm used to an old (1.3) version of CakePHP but the find() function is pretty basic and is designed to only return one row.
and yes, you definitely need to call the function with the id appended to the url, eg.
$planDetailsByCompany = $this->requestAction('/planDetails/pd_list_by_company/999');

Categories