accessing collections of cassandra in php - 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

Related

print mongodb array field values of document using 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 ...

Is it possible returning arrays from functions in php for-loop

The 1st for-loop is to retrieve $projSDE_1 which is employee ID and it's a value that changes every loop round.
$projSDE_1_IDs = [];
for($i=0; $i<db_rowcount();$i++)//1st for
{
$projSDE_1=db_get($i,8);
array_push($projSDE_1_IDs,$projSDE_1);
}
$projSDE_1_names = func_GetEmpNameNew($projSDE_1_IDs,$projSDE_1);
Next,the 2nd for-loop is going to retrieve all data and display it.All i need is each row will be able to display $projSDE_1_names by func_GetEmpNameNew($projSDE_1_IDs,$projSDE_1);
for($j=0; $j<db_rowcount();$j++)//2nd for
{
<tr >
<tbody>
<td style='width:5%'>".$no.". </a></td>
<td>".$projID." </td>
<td>".$projClient." </td>";
<td>".$projSDE_1_names." </td>";
</tbody>
</tr>
}//endfor
function to get $projSDE_1_names
function func_GetEmpNameNew($empIDs) {
$names = [];
foreach($empIDs as $empID){
$sqlEmp="select EmpID,LastName2_c from empbasic WHERE EmpID= '".$empID."'";
db_select($sqlEmp);
$rowcount=db_rowcount();
if(db_rowcount()>0){
for($f=0;$f<count($empIDs);$f++){
$empID=db_get($f,0);
$empName=db_get($f,1);
array_push($names, $empName);
}//for
}//if
}//foreach
return $names;
} // function
var_dump($projSDE_1_names); // Display the array to see if you get all the correct data.
The function is work fine and its able returns an array with the employees names..var_dump($projSDE_1_names);
So far this is the result i get - Result.
The list of name that displayed at the top is by
foreach ($projSDE_1_names as $projSDE_1_name) {
echo $projSDE_1_name.'-';
}
I need each name for each row.It listed 10 names from function and its suppose for 10 rows.All help appreciated
You are trying to fix the wrong issue.
Judging from your code, the initial list of values is retrieved from a relational database. The subsequent results are also retrieved from a relational database.
This alone is very wrong (unless the we are talking about 2 separate instances of DBMS which are unable to communicate directly). The right way to retrieve the 2 sets of data is using a JOIN on the data.
But that isn't the only howler in your code.
Repeatedly generating and executing a select statement in a loop is very bad practice. This would be solved by the same approach as the first issue above. However in the event of cases where the reference dataset does not originate on the same relational DBMS there are better ways to solve the problem. I would make a suggestion, but the db_ functions in your code are not standard PHP functions. The behaviour exposed in your code seems like a very cumbersome and limiting interface. Using mysqli you could simply....
function func_GetEmpNameNew($empIDs) {
global $db_handle;
$sqlEmp="select EmpID,LastName2_c from empbasic WHERE EmpID IN ("
. implode(",", $empID) // assuming the inputs are trusted and integer values
")";
$res=mysqli_query($db_handle, $sqlEmp);
return mysqli_fetch_all($res, MYSQLI_ASSOC);
}
As a side note you are using the order in which the data is returned in the orinal query as a means of indexing the result sets. As long as you are retrieving a single row each time, the data will matchup - but your code might retrieve zero, one or more than one row each time - again the solution is to run one query with a join. If you need to run queries against aseperate datasources, then index the array by a primary key attribute from the original dataset.

Reformat JSON arrays in MySQL database table using MySQL SELECT query (Wordpress)

I have a Wordpress build that uses CalderaWP forms. Unfortunately, the plugin's author has decided to store all checkbox entries as JSON arrays in the WP database and custom field values show up as "Array" instead of the actual text values.
I'd like to run a cron job that reformats these entries, but the first part is trying to figure out how to find and replace all values that are JSON objects.
I've written a function to get values from a specific table in the database, specifically the "wp_cf_form_entry_values" table. This function uses a regular expression in the SELECT query to find all values that begin with the "{" character. This is what I came up with to find JSON objects in the value field, but maybe there is a better way. Anyway, the function gets these values and reformats them from a JSON object to a list of individual items (i.e. various values that were checked in the submitted form).
Here is my current function:
function reformat_my_data() {
global $wpdb;
$data = $wpdb->get_results("SELECT value
FROM `wp_cf_form_entry_values`
WHERE `value` REGEXP '^[{].*$'
");
foreach($data as $key => $field) {
foreach($field as $val) {
if( is_json($val) ) {
$val = json_decode($val, true);
foreach($val as $checked) {
echo ' - ' . $checked . '<br/>';
}
}
}
}
}
reformat_my_data();
I also have another function to determine if the value is a JSON object:
function is_json($string) {
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
This works and outputs a list like this:
- checked #1
- checked #2
- checked #3
My question is: How do I get this newly formatted value back into the database? In other words, how do I do a mass replace of JSON type objects in the WP database?

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?)

Categories