print mongodb array field values of document using php - php

Hi I have a mongodb database where i store products and each product doc is like below :
Using php I want to print all instances of "user" from the "comments" array
What I tried :
$collection=$db->products;
$itemID = $_POST['itemID'];
$cursor = $collection->findOne(["id"=>$itemID]); //find an item
//print all user names who commented on item
foreach($cursor['comments'] as $c){
echo "<p> User : ".$c["user"]." </p>";
}
";
exit();
And I get :
Warning: Invalid argument supplied for foreach()
This is the first time I do this so I would appreciate your help

From the findOne() docs: As opposed to MongoCollection::find(), this method will return only the first result from the result set, and not a MongoCursor that can be iterated over.
( you need to use find().limit(1) to fetch single document if you want to iterate with forEach construction or you must remove the forEach method to be able to use the findOne() )
If you need to iterate over the comments arrray elements and there is nothing found in the database it will be a problem , so you need to check first if the comments exist ...
Before the end line there is ' "; ' that seems to need to be removed ...

Related

accessing collections of cassandra in php

here is the table I have created in cassandra database
create table followers(
username text,
followedby list<text>,
primary key(username));
using php I have to access the list of followers for a particular username($user="raj"). Below is the query I am using
$result=$session->execute(new Cassandra\SimpleStatement("select followedby from followers where username='$user'"));
I could not figure out how to store the result of the query using php so that all the elements in the list can be accessed one by one i.e. whether to use array or list in php. Below is one of the codes I tried.
foreach($result as $row)
{
$ans=$row['followed'];
echo $ans[0];
echo $ans[1];
}
but the code gave the following error:
Cannot use object of type Cassandra\Collection as array in C:\wamp64\www\LoginRegistrationForm\home.php on line 68
What is the correct method so that I can access all the elements in the list one by one?
foreach($result as $row)
{
foreach ($row['followed'] as $followed) {
echo " {$followed}" . PHP_EOL;
}
}
Driver returns object of type Collection and you are using it as an array.. hence it is giving you error.
Cassandra Collection in PHP

How do I store the result of sql without column name in php variable?

I’m trying to sore the result of sql in a variable. following is the sql(eloquent) :
$key = $request->input('product_key'); // from previous page
$category_id = ProductModel::select(‘category_id’)->where(‘product_id’, $key)->get();
echo $category_id;
but when i echo it , the output looks like [{“category_id”:301}]
i want only 301 to gets save in variable so that i can use it further ??
Basically i want to get all the products who's category_id is same as that of a given product. Note i have only prodcut_id.
Maybe you are refering to the value method. Find more about it here
https://laravel.com/docs/5.2/queries#retrieving-results
If you don't even need an entire row, you may extract a single value from a record using the value method. This method will return the value of the column directly:
example usage from the docs
$email = DB::table('users')->where('name', 'John')->value('email');
Try using Eloquent's pluck method: https://laravel.com/docs/5.2/collections#method-pluck
$key = $request->input('product_key');
$category_id = ProductModel::where('product_id', $key)->pluck('category_id')->all();
echo $category_id;
This should result in an array with a single element, which is the category_id you search for (or more elements in case key matches more than one row, but only values as you want).

Editing the object returned by $wpdb->get_results(SQL)

We have a nasty database call using the Wordpress function $wpdb->get_results(SQL).
After receiving the result in PHP, we need to make a few changes to the result.
So can anyone tell me how I can:
1) Remove specific rows from the get_results() returned object.
2) Change the values of the specific columns in specific rows in the returned object.
I.e. if the object returned is $nastyData, we need to:
1) Remove specific rows from $nastyData
2) Change the value of specific columns in specific rows in $nastyData, for example $nastyData->name for a specific row.
Any ideas?
I have thought about makeing get_results() return the data as an array, but that will create problems in other places in our code (where the code expects to receive an object).
Thanks,
Mads
To start with, your "Nasty database call" should be optimized to be less nasty. More specifically, only query the results you want so that you don't have to remove stuff afterwords. This is the best solution.
If you insist on trying to modify the objects, this is a workaround. According to the documentation, when returning objects, they are returned in one of two ways:
OBJECT - result will be output as a numerically indexed array of row objects.
OBJECT_K - result will be output as an associative array of row objects, using first column's values as keys (duplicates will be discarded).
So, knowing that the result is an array of objects, we can get to each individual instance using a foreach construct:
$results = $wpdb->get_results( $nastySQL );
foreach($results as $index => $result)
{
// Change name column to FirstName using copy and delete
$tmp = $result->name;
unset($result->name);
$result->FirstName = $tmp;
// Remove specific row
if( $result->name == "Tom")
{
unset($results[$index]);
}
}
Below code will replace the value coming from specific field of database table, if name field has value like Reo and you want to replace it with other name like John then you can to do this via below code
$results = $wpdb->get_results( $nastySQL );
foreach($results as $key => $value){
$results[$key]->name= 'John';
}
return $results;

Object Loop Not Working as Expected

I will be honest, I have just started learning objects and I am stuck.
I want to loop through an array of objects and display the name and description for each. But either nothing is displayed or it displays all the names first and then all the descriptions.
I am pulling the information from an API into the object:
// get tasks
foreach($tasksList->items as $task_details) {
$tasks_name[$task_details->id]=$task_details->name;
$tasks_desc[$task_details->id]=$task_details->description;
$tasks_details[$task_details->id]=$task_details->id;
$tasks_progress[$task_details->id]=$task_details->progress;
}
foreach($tasks_name as $taskid=>$my_task_name) {
echo "Task_Name: " . $my_task_name . "</br>";
$task_id = $task_details->id;
foreach($tasks_desc as $taskid1=>$my_task_desc) {
if($taskid==$task_details->id) {
echo "Task_Desc: " . $my_task_desc . "</br>";
}
}
}
Now what I don't understand is: inside the first foreach loop it is like a while loop while i=0, it checks $tasks_name[0], then $tasks_name[1] and so on.
However, I am not sure how to figure out what the id is in the current loop it is on, so I can tell it to only print the description of the current loop and not display all of them.
To be honest I am copying this from another example, but I don't quite understand it. I plan to study objects more, but this is holding me up on my current code:
foreach($tasks_desc as $taskid1=>$my_task_desc)
I understand it is looping through all the $tasks_desc and assigning the value to $my_task_desc but what is the signifigance of $taskid?
Sorry for the newbie questions. :)
This is poorly written. I would move on to another tutorial if it's a tutorial. Either that or the line that task_id is used was left out.
Anyway, tasks_name is an array of tasks indexed by the ID. So the outer loop in the second block loops over the keys/values of that array (the ID is the key, taskid. It was assigned by $task_details->id in the first loop above).
The second loop goes over all of the tasks again, but this time by description task_desc instead of by name. It's trying to find the task_desc with an ID that matches the ID of the task_name before (which would make it the same task).
That's unnecessary, though, because you could just store all of the entries (name, desc, etc.) in one array indexed by the ID instead of storing each in their own array:
(this is the first loop):
foreach($tasksList->items as $task_details) {
$all_tasks[$task_details->id]['name'] = $task_details->name;
$all_tasks[$task_details->id]['desc'] =$task_details->description;
// Don't need the ID again; it's the key
$all_tasks[$task_details->id]['progress'] = $task_details->progress;
}
However, you don't even need to do that, because you can just iterate over tasksList->items when you need to.
There's no need for two loops. To display name and description for each object, one loop is enough:
foreach($tasksList->items as $task_details) {
echo 'name: ', htmlspecialchars($task_details->name);
echo ', description: ', htmlspeciachars($task_details->description);
}
(I also don't understand why you want to store every object field in its own array first?)

PHP - associative array - blank row being added

I am trying to build Dynamic UI by getting data from DB using CodeIgniter but facing problem in constructing array.
Requirement:
Get parent menu items in an array. Then get child item corresponding to each parent item.
Code to get data for parent element::
$data['menu'] = $this->Menu->get_admin_menu_data();
This gives me 3 records
echo "before loop menu" . count($data['menu']) . "</br>"; //prints 3
Now I run a foreach loop for each parent item to retrieve it's child item
foreach($data['menu'] as $menu){
$data['menu']['menu_item'] = $this->Menu->get_admin_menu_item_data($menu->ad_menu_id);
echo "inside loop menu " . count($data['menu']) . "</br>"; //prints 4
}
As soon as I do this the count of menu increases to 4 resulting in error in UI.
I am new to PHP so now sure what is the best way to create a structure to hold this type of data.
Please help!!!!
If $data['menu'] contains 3 key/value pairs, but $data['menu']['menu_item'] is not set, your statement
$data['menu']['menu_item']
= $this->Menu->get_admin_menu_item_data($menu->ad_menu_id);
sets just this.
Thus count( $data['menu'] ) returns 4 elements afterwards - including the newly added 'menu_item' key.
I don't know CodeIgniter, but overwriting a static variable
$data['menu']['menu_item'] = "someting"
never makes sense. Where do you really want to store the result of
$this->Menu->get_admin_menu_item_data($menu->ad_menu_id);
? You can and should check the content of a variable using var_dump.

Categories