I'm making a query to a MongoDB and I only want the first object. I know I could use findOne, but I'm still confused where I'm going wrong.
This does not work:
if ($cursor->count() > 0) {
$image = $cursor->current();
// neither does this work
// $image = $cursor[0];
return $image;
} else {
return false;
}
//echo $image->filename;
// Throws error: Trying to access property of non-object image
This works though:
if ($cursor->count() > 0) {
$image = null;
foreach($cursor as $obj)
$image = $obj;
return $image;
} else {
return false;
}
How about this:
if ($cursor->count() > 0) {
$cursor->next();
$image = $cursor->current();
return $image;
} else {
return false;
}
Bonus: quote from the Doc page
public array MongoCursor::current (void)This returns NULL until
MongoCursor::next() is called.
Solution provided by raina77ow uses Mongo library which is marked as legacy.
At the moment there is only one way to get first element from cursor - use MongoDB\Driver\Cursor::toArray method:
$cursor = $collection->find();
$firstDocument = $cursor->toArray()[0];
Related
I am trying to check whether a generated string is in my database table or not.
If there is no duplicate I want to return and save it.
If there is a duplicate I want to generate a new string and save it
currently this function does not return me the generated token:
public function checkForHashDuplicate($string)
{
$newToken = '';
$inquiries = DB::table('inquiries')->get();
foreach($inquiries as $inquiryKey => $inquiryValue)
{
while($inquiryValue->android_device_token == $string)
{
$newToken = generateAlphanumericString();
if($newToken != $inquiryValue->android_device_token)
{
return $newToken;
}
}
}
}
$inquiry->android_device_token = $this->checkForHashDuplicate($hash);
A simplified version of your code is:
public function checkForHashDuplicate($string)
{
do {
// generate token
$newToken = generateAlphanumericString();
// find token in a DB
$duplicate = DB::table('inquiries')
->where('android_device_token', '=', $newToken)->first();
// if token is FOUND `$duplicate` has truthy value
// and `do-while` keeps running
// else `$duplicate` is falsy and `do-while` breaks
} while ($duplicate);
return $newToken;
}
Instead of using:
$inquiries = DB::table('inquiries')->get();
and loop, use where like:
$inquiries = DB::table('inquiries')->where('android_device_token', '=', $string)->get();
if( count($inquiries ) == 1 )
{
// found
}
else
{
// Not found, generate new one
}
You can check like this:
public function checkDuplicate($string){
$count = DB::table('inquiries')->where('android_device_token',$string)->count();
if($count==0){
// $string exists
return generateAlphanumericString();
}else{
// $string doesn't exists
return $string;
}
}
Now, use this function to assign value of $string or new token as
$inquiry->android_device_token = $this->checkForHashDuplicate($hash);
Hope you understand.
I have this code:
function saveField($field, $id, $module, $value)
{
$bean = BeanFactory::getBean($module, $id);
if (is_object($bean) && $bean->id != "") {
if ($bean->field_defs[$field]['type'] == "multienum") {
$bean->$field = encodeMultienumValue($value);
}else if ($bean->field_defs[$field]['type'] == "relate" || $bean->field_defs[$field]['type'] == 'parent'){
$save_field = $bean->field_defs[$field]['id_name'];
$bean->$save_field = $value;
if ($bean->field_defs[$field]['type'] == 'parent') {
$bean->parent_type = $_REQUEST['parent_type'];
$bean->fill_in_additional_parent_fields(); // get up to date parent info as need it to display name
}
}else{
$bean->$field = $value;
}
//return here will work
$bean->save(); //this works
//nothing works here
return getDisplayValue($bean, $field);
} else {
return false;
}
}
The problem here is that anything under
$bean->save()
will not work. But I know that save is working as the values are being updated. So how can I debug this problem?
I already tried:
return var_dump($bean->save());
return print_r($bean->save());
if($bean->save()){
return "1";
}else{
return "2";
}
And none of those in the above worked I still get nothing in my return.
There is likely something such as an after_save logic hook that is executing and either causing a fatal error or doing an exit.
Try using xdebug, it should allow you to investigate further into the save method that fails.
I have a function that returns either a value into a variable if it is successful or it returns an errors array. see part of it below.
function uploadEmploymentDoc($var, $var2){
$ERROR = array();
if(empty($_FILES['file']['tmp_name'])){
$ERROR[] = "You must upload a file!";
}
//find the extensions
$doctypeq = mysql_query("SELECT * FROM `DocType` WHERE `DocMimeType` = '$fileType'");
$doctype = mysql_fetch_array($doctypeq);
$docnum = mysql_num_rows($doctypeq);
if($docnum == 0){
$ERROR[] = "Unsupported file type";
}
if(empty($ERROR)){
// run my code
return $var;
} else{
return $ERROR;
}
then when I run my code
$result = uploadEmploymentDoc(1, 2);
if($result !=array()){
// run code
} else {
foreach($result as $er){
echo $er."<br>";
}
}
Now my question is this. Why is my function running my code and not showing me an error when I upload an unsupported document type. Am I defining my foreach loop correctly? For some reason I cant get my errors back.
you should write like this-
if(is_array($result)){
foreach($result as $er){
echo $er."<br>";
}
} else {
//your code for handling error
}
You can get more info :http://us2.php.net/is_array
Try use
$result = uploadEmploymentDoc(1, 2);
if(!is_array($result)){
// run code
} else {
foreach($result as $er){
echo $er."<br>";
}
}
Probably will be better add parameter by reference to function for the errors array. From function return "false" if error and value if no error occurred.
I have been researching this for a while and can't seem to find the problem with my code. I am attempting to get the price of an item and this works great if there is a price, but if the price is missing it throws an error.
Here is the code:
/* Amazon Offers ALGORITHM */
$parsed_xml = amazon_xml($isbn);
$current = $parsed_xml->ListMatchingProductsResult->Products->Product;
$asin = $current->Identifiers->MarketplaceASIN->ASIN;
// get information based on the items ASIN
$price_xml = amazonPrice_xml($asin);
if($price_xml) {
while(count($lowestPrices) < 2)
{
// check to see if there are values
if(xml_child_exists($parsed_xml, $current->AttributeSets->children('ns2', true)->ItemAttributes->ListPrice->Amount))
{
$listPrice = $current->AttributeSets->children('ns2', true)->ItemAttributes->ListPrice->Amount;
} else {
$listPrice = 0;
}
$currentPrice = $price_xml ->GetLowestOfferListingsForASINResult->Product->LowestOfferListings->LowestOfferListing;
print_r($listPrice);
My function to check for child nodes is:
function xml_child_exists($xml, $childpath)
{
$result = $parsed_xml->xpath($childpath);
if (count($result)) {
return true;
} else {
return false;
}
}
try this to check if child node exists
function xml_child_exists($xml, $childpath)
{
//$result = $parsed_xml->xpath($childpath); $parsed_xml variable?
$result = $xml->xpath($childpath);
if (isset($result)) { // changed from count to isset
return TRUE;
} else {
return FALSE;
}
}
Use property_exists()
I'm using it to check duplicated child while adding new child into xml using SimpleXML. It should work for you. If you just pass in the child name, and its parent.
function xml_child_exists($xml, $child)
{
return property_exists($xml, $child);
}
I am working with SilverStripe, and I am working on making a newspage.
I use the DataObjectAsPage Module( http://www.ssbits.com/tutorials/2012/dataobject-as-pages-the-module/ ), I got it working when I use the admin to publish newsitems.
Now I want to use the DataObjectManager Module instead of the admin module to manage my news items. But this is where the problem exists. Everything works fine in draft mode, I can make a new newsitem and it shows up in draft. But when I want to publish a newsitem, it won't show up in the live or published mode.
I'm using the following tables:
-Dataobjectaspage table,
-Dataobjectaspage_live table,
-NewsArticle table,
-NewsArticle_Live table
The Articles have been inserted while publishing in the Dataobjectaspage table and in the NewsArticle table... But not in the _Live tables...
Seems the doPublish() function hasn't been used while 'Publishing'.
So I'm trying the use the following:
function onAfterWrite() {
parent::onAfterWrite();
DataObjectAsPage::doPublish();
}
But when I use this, it gets an error:
here is this picture
It seems to be in a loop....
I've got the NewsArticle.php file where I use this function:
function onAfterWrite() {
parent::onAfterWrite();
DataObjectAsPage::doPublish();
}
This function calls the DataObjectAsPage.php file and uses this code:
function doPublish() {
if (!$this->canPublish()) return false;
$original = Versioned::get_one_by_stage("DataObjectAsPage", "Live", "\"DataObjectAsPage\".\"ID\" = $this->ID");
if(!$original) $original = new DataObjectAsPage();
// Handle activities undertaken by decorators
$this->invokeWithExtensions('onBeforePublish', $original);
$this->Status = "Published";
//$this->PublishedByID = Member::currentUser()->ID;
$this->write();
$this->publish("Stage", "Live");
// Handle activities undertaken by decorators
$this->invokeWithExtensions('onAfterPublish', $original);
return true;
}
And then it goes to DataObject.php file and uses the write function ():
public function write($showDebug = false, $forceInsert = false, $forceWrite = false, $writeComponents = false) {
$firstWrite = false;
$this->brokenOnWrite = true;
$isNewRecord = false;
if(self::get_validation_enabled()) {
$valid = $this->validate();
if(!$valid->valid()) {
// Used by DODs to clean up after themselves, eg, Versioned
$this->extend('onAfterSkippedWrite');
throw new ValidationException($valid, "Validation error writing a $this->class object: " . $valid->message() . ". Object not written.", E_USER_WARNING);
return false;
}
}
$this->onBeforeWrite();
if($this->brokenOnWrite) {
user_error("$this->class has a broken onBeforeWrite() function. Make sure that you call parent::onBeforeWrite().", E_USER_ERROR);
}
// New record = everything has changed
if(($this->ID && is_numeric($this->ID)) && !$forceInsert) {
$dbCommand = 'update';
// Update the changed array with references to changed obj-fields
foreach($this->record as $k => $v) {
if(is_object($v) && method_exists($v, 'isChanged') && $v->isChanged()) {
$this->changed[$k] = true;
}
}
} else{
$dbCommand = 'insert';
$this->changed = array();
foreach($this->record as $k => $v) {
$this->changed[$k] = 2;
}
$firstWrite = true;
}
// No changes made
if($this->changed) {
foreach($this->getClassAncestry() as $ancestor) {
if(self::has_own_table($ancestor))
$ancestry[] = $ancestor;
}
// Look for some changes to make
if(!$forceInsert) unset($this->changed['ID']);
$hasChanges = false;
foreach($this->changed as $fieldName => $changed) {
if($changed) {
$hasChanges = true;
break;
}
}
if($hasChanges || $forceWrite || !$this->record['ID']) {
// New records have their insert into the base data table done first, so that they can pass the
// generated primary key on to the rest of the manipulation
$baseTable = $ancestry[0];
if((!isset($this->record['ID']) || !$this->record['ID']) && isset($ancestry[0])) {
DB::query("INSERT INTO \"{$baseTable}\" (\"Created\") VALUES (" . DB::getConn()->now() . ")");
$this->record['ID'] = DB::getGeneratedID($baseTable);
$this->changed['ID'] = 2;
$isNewRecord = true;
}
// Divvy up field saving into a number of database manipulations
$manipulation = array();
if(isset($ancestry) && is_array($ancestry)) {
foreach($ancestry as $idx => $class) {
$classSingleton = singleton($class);
foreach($this->record as $fieldName => $fieldValue) {
if(isset($this->changed[$fieldName]) && $this->changed[$fieldName] && $fieldType = $classSingleton->hasOwnTableDatabaseField($fieldName)) {
$fieldObj = $this->dbObject($fieldName);
if(!isset($manipulation[$class])) $manipulation[$class] = array();
// if database column doesn't correlate to a DBField instance...
if(!$fieldObj) {
$fieldObj = DBField::create('Varchar', $this->record[$fieldName], $fieldName);
}
// Both CompositeDBFields and regular fields need to be repopulated
$fieldObj->setValue($this->record[$fieldName], $this->record);
if($class != $baseTable || $fieldName!='ID')
$fieldObj->writeToManipulation($manipulation[$class]);
}
}
// Add the class name to the base object
if($idx == 0) {
$manipulation[$class]['fields']["LastEdited"] = "'".SS_Datetime::now()->Rfc2822()."'";
if($dbCommand == 'insert') {
$manipulation[$class]['fields']["Created"] = "'".SS_Datetime::now()->Rfc2822()."'";
//echo "<li>$this->class - " .get_class($this);
$manipulation[$class]['fields']["ClassName"] = "'$this->class'";
}
}
// In cases where there are no fields, this 'stub' will get picked up on
if(self::has_own_table($class)) {
$manipulation[$class]['command'] = $dbCommand;
$manipulation[$class]['id'] = $this->record['ID'];
} else {
unset($manipulation[$class]);
}
}
}
$this->extend('augmentWrite', $manipulation);
// New records have their insert into the base data table done first, so that they can pass the
// generated ID on to the rest of the manipulation
if(isset($isNewRecord) && $isNewRecord && isset($manipulation[$baseTable])) {
$manipulation[$baseTable]['command'] = 'update';
}
DB::manipulate($manipulation);
if(isset($isNewRecord) && $isNewRecord) {
DataObjectLog::addedObject($this);
} else {
DataObjectLog::changedObject($this);
}
$this->onAfterWrite();
$this->changed = null;
} elseif ( $showDebug ) {
echo "<b>Debug:</b> no changes for DataObject<br />";
// Used by DODs to clean up after themselves, eg, Versioned
$this->extend('onAfterSkippedWrite');
}
// Clears the cache for this object so get_one returns the correct object.
$this->flushCache();
if(!isset($this->record['Created'])) {
$this->record['Created'] = SS_Datetime::now()->Rfc2822();
}
$this->record['LastEdited'] = SS_Datetime::now()->Rfc2822();
} else {
// Used by DODs to clean up after themselves, eg, Versioned
$this->extend('onAfterSkippedWrite');
}
// Write ComponentSets as necessary
if($writeComponents) {
$this->writeComponents(true);
}
return $this->record['ID'];
}
Look at the $this->onAfterWrite();
It probably goes to my own function on NewsArticle.php and there starts the loop! I'm not sure though, so i could need some help!!
Does anyone knows how to use the doPublish() function?
The reason that is happening is that in the DataObjectAsPage::publish() method, it is calling ->write() - line 11 of your 3rd code sample.
So what happens is it calls ->write(), at the end of ->write() your onAfterWrite() method is called, which calls publish(), which calls write() again.
If you remove the onAfterWrite() function that you've added, it should work as expected.
The doPublish() method on DataObjectAsPage will take care of publishing from Stage to Live for you.