A bit of weird issue - I am looking to enter data into two separate
collections (same db) and I am getting totally weird results. I am
sure it is the way I am doing this but it is the results which have me
a bit baffled.
Here is a snippet of what I am trying to accomplish:
$mynewconnection = new Mongo(); // create new mongo connection
$collectionDB = $mynewconnection->Datadb; // select db
$collectionA = $collectionDB->DataA; // select collectionA
$collectionB = $collectionDB->DataB; // select collectionB
/* Go off and chop up data and create CriteriaA/B */
$insertA = $collectionA->insert($criteriaA);
$insertB = $collectionB->insert($criteriaB);
So what I am trying accomplish is to enter part of the data set into
one collection and the other part of the dataset into another
collection. What is happening is that sometimes the data will be
entered into Both collections (as desired) and other times data will
be entered into just collectionA and yet other times data will be
entered into just collectionB.
Anyone have any ideas on what I am missing or what would be causing
this strange behavior?
When you fire a query to write something to MongoDB, it does not confirm whether the data is written to database or not. You need to see the page of php's manual for Write Concerns.
The link for the same is: http://www.php.net/manual/en/mongo.writeconcerns.php
Related
I've been spent hours trying to figure out how I'm supposed to get around this error in my scenario. I'm trying to run a few queries in sequence.
I have read: codeigniter : Commands out of sync; you can't run this command now, however I am not able to update /system/database/drivers/mysqli/mysqli_result.php
I've tried:
$this->db->reset_query();
$this->db->close();
$this->db->initialize();
$this->db->reconnect();
mysqli_next_result( $this->db->conn_id );
$query->free_result();
But they either give me the same error, or different errors which I will detail in the comments of my code.
The way my code is organized- I have a make_query method that takes a bunch of search options and figures out which tables to join and fields to search based on those. Sometimes, I just want to count results, sometimes I want all of the resulting data, sometimes I just want distinct values for certain fields or to group by certain fields. So I call make_query with my options, and then decide what to select afterwards. I have also been saving my query text to report, so that users can see what query is being run.
One interesting thing I have noted is that when I have no options set (ie there are no WHERE clauses in my SQL), I do not get this error and the multiple queries are able to run with no problem!
Here is my code:
//Get rows from tblPlots based on criteria set in options array
public function get_plot_data($options=array()){
$this->db->save_queries = TRUE;
log_message('debug','before make query 1 get plot data');
$this->make_query($options,'plot');
log_message('debug','after make query 1 get plot data');
$this->db->distinct();
//Now, set select to return only requested fields
if (!empty($options['fields']) and $options['fields']!="all" ){
//Because other tables could be joined, add table name to each select
array_walk($options['fields'], function(&$value, $key) { $value = 'tblPlots.'.$value;} );
$this->db->select($options['fields']);
}
if (!empty($options['limit']) and $options['limit']>0){
$this->db->limit($options['limit'], $options['offset']);
}
//Get the resulting data
$result=$this->db->get('tblProgram')->result();
$query_text = $this->db->last_query(); //tried removing this but didn't help
log_message('debug','query text '.$query_text);
$this->db->save_queries = FALSE;
//get the number of rows
//$this->db->reset_query();
//$this->db->close();
//$this->db->initialize();
//$this->db->reconnect();
//mysqli_next_result( $this->db->conn_id );
//$this->db->free_result(); //Call to undefined method CI_DB_mysqli_driver::free_result()
//$result->free_result(); //Call to a member function free_result() on array
log_message('debug','before make query 2');
$this->make_query($options,"plot");
$this->db->select('pkProgramID');
log_message('debug','before count results');
//this is where my code errors out trying to do the next step:
$count=$this->db->count_all_results('tblProgram');
}
I'm not including the code for make_query because it is long and calls other functions, but it runs successfully the first time and outputs the SQL query I would expect. If it would be helpful, I can include that code as well.
I'm not sure how to correctly call free_result() given that the CI documentation only gives an example using query('SQL QUERY') and I am building the query using Active Record, so I'm not sure how to use free result in my scenario? Maybe that's the issue?
$query2 = $this->db->query('SELECT name FROM some_table');
$query2->free_result();
Thank you for any help!
I ended up posting on a CI forum that suggested https://www.youtube.com/watch?v=yPiBhg6r5B0 which worked! Also I ended up having to join my tables differently to avoid timeouts (I think I was having trouble because I was using AJAX to call many queries asynchronously and one of them was timing out). Hope this helps someone!
I've got SugarCrm plugin which is exporting data to external service. I'm using logic hooks for updated/deleted/new Contacts, but I've got problem with synchronizing already existing data. I have to extract all the data from the SugarCRM and there are two SugarBean methods I've tried to use: get_full_list() and get_list(). First one gives me the full Contact list, but I need to send it in batches 1000 Contacts in one Json max, the second method returns only first page of the Contacts (depends on config settings 10 - 1000max entries).
I'm using this method ATM:
// prepare contacts data from SugarBean
$bean = BeanFactory::getBean($module);
$contactResults = $bean->get_full_list();
Then foreach on $contactResults and save the data I want to the required format and send it as a Json via postrequest. I've tried to find the solution to split it into batches, but Im stuck :( Neither get_full_list or get_list seems to work for me.
Any suggestions? Maybe someone solved this issue already?
Thanks in advance!
It sounds to me like your problem is creating batches? If not please be more specific about what isn't working.
For splitting an array into batches, you may want to have a look at https://php.net/manual/en/function.array-chunk.php
Also get_list supports retrieving later pages. It is defined like this: function get_list($order_by = "", $where = "", $row_offset = 0, $limit=-1, $max=-1, $show_deleted = 0, $singleSelect=false, $select_fields = array()).
That means for the second page you could specify $row_offset = 1000, for the third page make it 2000, etc. So basically run a loop that calls get_list with $limit = 1000 and increases an initial $row_offset of 0 by 1000 after each iteration, until less than 1000 records or null is returned by the function.
Here are some general hints if you run into problems with processing those beans:
If the problem you're having is incomplete data, try loading each bean manually by using its ID. Some Sugar functions don't load all (special) fields by default.
If things seem to just fail for no reason, make sure to check your PHP log for errors. Maybe loading as many beans at once could possibly cause problems with your PHP's max_execution_time or memory_limit.
In FileMaker I have (a.o.) two related tables, where Betreuer_id of table "studentpaper" refers to id of table "Betreuer".
With help of FileMaker's PHP API, I want to access a record in "studentpaper" including the releated fields. Howerver, the later poses a problem. Consider the following PHP code:
$findCommand =& $fm->newFindAllCommand('studentpaper');
$result = $findCommand->execute();
$records = $result->getRecords();
$record = $records[0];
echo $record->getField('Titel'); // okay
echo $record->getField('Betreuer_id'); // okay
echo $record->getField('Betreuer::Name');
// ERROR: get empty string, even related record has a non-empty field
I have expected for "Betreuer::Name" the correct related result, as usually in FileMaker (and as I get in studentpaper's layout). However, I get only an empty string.
What am I doing wrong? Does the relation in FileMaker's PHP-API differs from the "usual" FileMaker approach?
In case anybody is interested, I found the solution on my own.
The problem was that the field wasn't defined (in the layout) as normal text input, but as selection field resticted by a value list.
Thus, one needs to access the value not via the usual getField function but by one of the functions related to value lists. In my case, getValueListTwoFields did the job.
I have been working with a small team on a small project about fiction world building. I have been assigned with the task of managing triggers/chained behavior of entities (rocks/places/items) that can be triggered in many ways such as throwing a magic rock into the lake and monster X will appear, and continue to trigger the things in a chain until it reaches the end.
I have tried this
$Trigger_123 = new stdClass();
$Trigger_123->name = "Name";
$Trigger_123->renderOn = ? // (object_345->throwedInLakeX) ?
How can I store this in MySQL? Can I have it checked if its a chain part? Also I tried MySQL triggers but I can't find a way to execute PHP on those triggers. Running PHP code on update or delete for example.
Cron jobs was not a option because many things will be added in the future and cron jobs will take a lot of time to finish, I was hoping of finding a more php-based solution.
Edited (adding some additional information)
I tried to implement this in many ways. I ended up with a system of dependecies pretty much like debian packages which I believe is not suited for this.
Database structure
Table "object"
--------------
ID (int)
Name (varchar)
Table "triggers"
----------------
ID (int)
Name (varchar)
Data (blob) // usually, I store php code and use eval to run
Table "attributes"
------------------
ID (int)
attribute (varchar)
value (blob)
Table "object_has_triggers"
---------------------------
ID (int)
ObjectID (int)
TriggerID (int)
Table "object_has_attributes"
-----------------------------
ID (int)
ObjectID (int)
AttributeID (int)
What I want as a result is to make a PHP code snippet execute each time
A database transaction , before is submitted and after to database
A object that has X triggers attached to it, resolve them
Each Trigger that is triggered by X be checked if all dependecies to it are satisfied
Question:
Is something like this even possible to build with PHP Or should I try other scripting languages like python?
what i want as a result is to make a PHP code snippet execute each time
A database transaction , before is submitted and after to database
You should call PHP function in trigger. Write all logic in PHP which required to invoke.
A object that has X triggers attached to it, resolve them
A object that has X triggers attached to it, rather convert it into PHP code or resolve it in PHP.
Each Trigger that is triggered by X be checked if all dependecies to it are satisfied
You can make one database table for saving responses after successful completing trigger. And at last you can check all dependencies are satisfied or not.
For calling PHP function from trigger, see different answers of following posts for different types of solutions.
Invoking a PHP script from a MySQL trigger
A PHP code snippet execute each time a database transaction , before is submitted and after to database
Don't reinvent the wheel, this has an incredible simple solution: have a layer on top of your database calls.
Instead of querying your database directly, call a function (perhaps in an object) that handles the database insertion of triggers. And it is right there that you can add your code to pre and post- process your triggers in whichever way you please.
function processDatabaseInsertion($trigger) {
//Preceding code goes here
//Database transaction goes here
//Post-processing code goes here
}
$Trigger_123 = new stdClass();
$Trigger_123->name = "Name";
$Trigger_123->renderOn = $object_345->throwedInLakeX;
processDatabaseInsertion($Trigger_123);
Over simplified, but you get the idea. I would recommend writing a custom class for your triggers but I wrote it in a procedural style since I don't know if you are familiar with OOP.
A PHP code snippet execute each time a object that has X triggers attached to it, resolve them
Same principle as before. If you use PHP >= 5.3, you can spice it up a bit using closures:
function processDatabaseInsertion($trigger) {
//Preceding code goes here
$trigger->renderOn();
//Database transaction goes here
//Post-processing code goes here
}
$Trigger_123 = new stdClass();
$Trigger_123->name = "Name";
$Trigger_123->renderOn = function() use ($Trigger_123) { doAwesomeThing($Trigger_123); }
processDatabaseInsertion($Trigger_123);
Or otherwise go for a more traditional approach:
function processDatabaseInsertion($trigger) {
//Preceding code goes here
switch($trigger->renderOn) {
case "awesomeThing":
doAwesomeThing($trigger);
break;
case "anotherThing":
break;
default:
break;
}
//Database transaction goes here
//Post-processing code goes here
}
$Trigger_123 = new stdClass();
$Trigger_123->name = "Name";
$Trigger_123->renderOn = "awesomeThing";
processDatabaseInsertion($Trigger_123);
Each Trigger that is triggered by X be checked if all dependecies to
it are satisfied
Can easily be handled by the methods above with some more PHP logic as you will be able to tell. You may want to have for instance a generic function called every time you need to process a trigger which in turns check if dependencies are satistifed and runs the specific trigger if so.
Either way there are better ways to tackle this problem than to use eval or some mysql trigger hacking as you can see :)
I am allowing users to vote on content, so I need to save a user input to my database, and then get a COUNT() of the input to return back.
The voting works fine, but reading the results back always returns false. The only work around I have found is to rebuild the database connection a second time to count the votes. Is there any other way to do this?
Here is my code:
$vote = $conn->prepare($voteSQL);
$vote->execute(array(':postId'=>$voteId
, ':voterId'=>$userId
, ':voteType'=> $voteDir
,':voteType2'=> $voteDir
,':voteType3'=> $voteDir));
$tallyVotes = $conn->prepare($tallySQL);
$tallyVotes->execute(array(':postId'=>$voteId));
$updatedTally = $tallyVotes->fetch();