MongoDb SearchQuery Issue - php

I have a database and a table user. when i perform below code i got output as below.
$searchQuery = array('userID' => '2');
$collection = $db->mydatabase->users;
$cursor = $collection->find()->limit(2);
foreach ($cursor as $doc) {
var_dump($doc);
}
Output:
array(4) {
'_id' =>
class MongoId#8 (1) {
public $$id =>
string(24) "56c8216d7f8b9a0e148b4567"
}
'userID' =>
int(7)
'lastTimeOnline' =>
string(19) "2016-02-20 01:48:53"
'displayName' =>
string(0) ""
}
array(4) {
'_id' =>
class MongoId#9 (1) {
public $$id =>
string(24) "56c8216d7f8b9a0e148b4568"
}
'userID' =>
int(2)
'lastTimeOnline' =>
string(19) "2016-02-20 01:48:53"
'displayName' =>
string(0) ""
}
Now i need to find only those records whose userID is 2, so i change the code as below.
$searchQuery = array('userID' => '2');
$collection = $db->mydatabase->users;
$cursor = $collection->find($searchQuery)->limit(2);
foreach ($cursor as $doc) {
var_dump($doc);
}
but now the output is blank :-(
I have two doubts.
A) why 2nd code to fetch userId=2 is not working
B)why on both cases var_dump($cursor) is giving below output and why not detail of $doc
class MongoCursor#5 (0) {
}

Seems like the userID in database is saved as Integer and your are trying to query using a string parameter, try to change the query array to the following:
$searchQuery = array('userID' => 2);

You are storing the userId as an integer and in the query you are using a string due to which you are find nothing so instead of writing 2 like this '2' write it like this 2

Related

How to store associative array in Laravel

I'm new to Laravel, and I want to store this array in DB.
This is the php code of my array:
$socialNetwork = array();
$socialNetwork[0]["name"]= "Facebook";
$socialNetwork[0]["account"]= "facebook_account";
$socialNetwork[1]["name"]= "Twitter";
$socialNetwork[1]["account"]= "twitter_account";
$socialNetwork[2]["name"]= "Instagram";
$socialNetwork[2]["account"]= "insta_account";
The var_dump() looks like this:
array(3) {
[0] => array(2) {
["name"] => string(8) "Facebook"
["account"] => string(16) "facebook_account"
}
[1] => array(2) {
["name"] => string(7) "Twitter"
["account"] => string(15) "twitter_account"
}
[2] => array(2) {
["name"] => string(9) "Instagram"
["account"] => string(13) "insta_account"
}
}
I've tried several things but I can't get it to work!
Please help with the code. The table name is socialAccounts
Add a column in your database for this field; a JSON or TEXT type will do the job.
Next, you should add the column to the $casts array on your SocialAccount model:
protected $casts = [
'facebook_account' => 'array',
];
Now, whenever you retrieve this value, it will be deserialized for you.
To store the value, just use json_encode():
$social_account->facebook_account = json_encode($facebookArrayData);
$social_account->save();
You can read more on attribute casting in the docs; https://laravel.com/docs/7.x/eloquent-mutators#attribute-casting

Make multidimensional array with php and pdo

i want to edit a script i found online. is has an hardcoded array like this.
$servers = array(
'Google Web Search' => array(
'ip' => '',
'port' => 80,
'info' => 'Hosted by The Cloud',
'purpose' => 'Web Search'
),
'Example Down Host' => array(
'ip' => 'example.com',
'port' => 8091,
'info' => 'ShittyWebHost3',
'purpose' => 'No purpose'
)
);
Result:
array(2) {
["Google Web Search"]=>
array(4) {
["ip"]=>
string(0) ""
["port"]=>
int(80)
["info"]=>
string(19) "Hosted by The Cloud"
["purpose"]=>
string(10) "Web Search"
}
["Example Down Host"]=>
array(4) {
["ip"]=>
string(11) "example.com"
["port"]=>
int(8091)
["info"]=>
string(14) "ShittyWebHost3"
["purpose"]=>
string(10) "No purpose"
}
}
I put this data in a database and want to make the same array but i dont seem to get it working
This is the code i added to make an array:
$query ="SELECT name, ip, port, hosting FROM sites";
$select = $conn->prepare($query);
$select->execute(array());
$testing = array();
while($rs = $select->fetch(PDO::FETCH_ASSOC)) {
$testing[] = array($rs['name'] => array('ip'=> $rs['ip'], 'port'=> $rs['port'], 'hosting'=> $rs['hosting']));
}
The result from this is:
array(2) {
[0]=>
array(1) {
["Google Web Search"]=>
array(3) {
["ip"]=>
string(10) "google.com"
["port"]=>
string(2) "80"
["hosting"]=>
string(19) "Hosted by The Cloud"
}
}
[1]=>
array(1) {
["Example Down Host"]=>
array(3) {
["ip"]=>
string(11) "example.com"
["port"]=>
string(2) "09"
["hosting"]=>
string(14) "ShittyWebHost3"
}
}
}
is there a way to make the bottom array the same as the top array, i dont want to edit the whole script, this seems easier.
You are appending a new integer indexed element with [] and then adding 2 nested arrays. Instead, add the name as the key:
$testing[$rs['name']] = array('ip'=> $rs['ip'],
'port'=> $rs['port'],
'hosting'=> $rs['hosting']);
Since you specify the columns in the query and they are the same as the array keys, then just this:
$testing[$rs['name']] = $rs;
When you assign a value to an array you use the syntax $arr[key] = $value. If you omit the key during the assignment, $value will be assigned to the next available integer key of the array, starting from 0.
This is an example of how it works:
$arr = array();
$arr[] = 'one';//Empty, so insert at 0 [0=>'one']
$arr[] = 'two';//Last element at 0, so use 1 [0=>'one',1=>'two']
$arr[6]= 'three';//Key is used, so use key [0=>'one',1=>'two',6=>'three']
$arr[] = 'four';//Max used integer key is 6, so use 7
print_r($arr);//[0=>'one',1=>'two',6=>'three',7=>'four']
So, when in your code you are using
$testing[] = array(
$rs['name'] => array(
'ip'=> $rs['ip'],
'port'=> $rs['port'],
'hosting'=> $rs['hosting']
)
);
You are assigning the newly created array to the positions 0,1,2,..N.
To avoid this, just specify the key explicitly, using the value you really want, like
$testing['name'] => array(
'ip'=> $rs['ip'],
'port'=> $rs['port'],
'hosting'=> $rs['hosting']
);
You can read more about arrays in the documentation
Side note
If you don't mind having an extra column in the generated arrays, you can rewrite entirely your code this way:
$query ="SELECT name, ip, port, hosting FROM sites";
$results = $conn->query($query)->fetchAll(PDO::FETCH_ASSOC);
$testing = array_column($results,null,'name');
It's slightly slower, but very handy in my opinion, PDOStatement::fetchAll retrieves all the data at once and array_column using null as second parameter does reindex the array with the wanted column as key.
PDOStatement::fetchAll
array_column

Php array foreach

I am trying to fetch some data from an API and put it into an array and then to MySQL.
My Code:
$find_sql = "SELECT * FROM `scrape`";
$users_to_scrape = $app['db']->fetchAll($find_sql);
$instagram = $app['instagram'];
$oauth = json_decode(file_get_contents($app['oauth_path']));
$instagram->setAccessToken($oauth);
foreach($users_to_scrape as $user_to_scrape) {
printf("Getting info for %s <%s>\n", $user_to_scrape['instagram_id'], $user_to_scrape['user_name']);
$follows = $instagram->getUser($user_to_scrape['instagram_id'], 999);
foreach($follows->data as $follow) {
echo var_dump($follows);
$data = array(
'instagram_id' => $follow->id,
'followed_by_instgram_id' => $user_to_scrape['instagram_id'],
'user_name' => $follow->username,
'full_name' => iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($follow->full_name)),
'profile_picture' => $follow->profile_picture,
'followers' => $follow->counts->followed_by,
'follows' => $follow->counts->follows
);
printf("+ %s <%s>\n", $data['instagram_id'], $data['user_name']);
//skapa tabell med follows (instagram_id,
if ($follow->counts->followed_by >= "30000") {
$app['db']->insert('follows', $data);
}
}
}
The Vardump returns this:
object(stdClass)#111 (2) {
["meta"]=>
object(stdClass)#112 (1) {
["code"]=>
int(200)
}
["data"]=>
object(stdClass)#113 (7) {
["username"]=>
string(9) "Dimbos"
["bio"]=>
string(97) "•Have fun in life Contact: info#skogen.com"
["website"]=>
string(24) "http://www.life.com"
["profile_picture"]=>
string(106) "https://xxertt.com/hphotos-ak-xaf1/t51.2885-19/11311351_362556250614181_543_a.jpg"
["full_name"]=>
string(10) "Dimbo"
["counts"]=>
object(stdClass)#114 (3) {
["media"]=>
int(113)
["followed_by"]=>
int(256673)
["follows"]=>
int(345)
}
["id"]=>
string(8) "38353560"
}
}
And the error I receive is this:
Notice: Trying to get property of non-object in /var/www/script.php on line 40
On line 40 we have this:
'instagram_id' => $follow->id,
I also get error on the following set arrays.
Can't really figure it out.
Because $follows->data is a stdClass object, iterating it with foreach will loop over each of its properties individually, returning the value of each property. This means that though id is present in the loop, it is merely the last data element of the loop, inaccessible by its property name.
Using the foreach, the iterator value of $follow results directly in the values rather than properties, as in:
// Value of $follow on each loop iteration:
"Dimbos"
"•Have fun in life Contact: info#skogen.com"
"http://www.life.com"
// etc...
You don't need the foreach loop. Instead, access each element of $follows->data directly:
// Remove the foreach loop
$data = array(
// Each property is directly accessible in $follows->data
'instagram_id' => $follows->data->id,
'followed_by_instgram_id' => $user_to_scrape['instagram_id'],
'user_name' => $follows->data->username,
'full_name' => iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($follows->data->full_name)),
'profile_picture' => $follows->data->profile_picture,
'followers' => $follows->data->counts->followed_by,
'follows' => $follows->data->counts->follows
);
printf("+ %s <%s>\n", $data['instagram_id'], $data['user_name']);
//skapa tabell med follows (instagram_id,
if ($follows->data->counts->followed_by >= "30000") {
$app['db']->insert('follows', $data);
}
You could create a variable that references the data property, allowing you to access those inner properties with less code, but I don't see it as necessary.
// Refer to data in $follow
$follow = $follows->data;
echo $follow->id;
echo $follow->counts->followed_by;
// etc...

Extracting (searching in) a subset of a dictionary?

I want to make a dictionary (or list) that is a subset of another dictionary in PHP. Please look below at my code written in Python:
ThePythons = {
'GC': 'Graham Chapman',
'JC': 'John Cleese',
'EI': 'Eric Idle',
'MP': 'Michael Palin'
}
query = ['EI', 'JC']
output = [[item,ThePythons[item]] for item in query if item in ThePythons]
print(output)
And output is:
[['EI', 'Eric Idle'], ['JC', 'John Cleese']]
I don't know how to accomplish the same functionality in in PHP. Please give me the corresponding code in PHP. Many thanks in advance!
The following should work:
<?php
$thePythons = array(
'GC' => 'Graham Chapman',
'JC' => 'John Cleese',
'EI' => 'Eric Idle',
'MP' => 'Michael Palin'
);
$query = array(0 => 'EI', 1 => 'JC');
$resultList = array();
for ($i=0; $i<sizeof($query); $i++) {
$resultList[$i] = array($query[$i] => $thePythons[$query[$i]]);
}
var_dump($resultList);
?>
Output
array(2) {
[0]=>
array(1) {
["EI"]=>
string(9) "Eric Idle"
}
[1]=>
array(1) {
["JC"]=>
string(11) "John Cleese"
}
}

MongoDB returns empty on find() but content on findOne or when using count()

I am using mongoDB for a new project at work and I got into some troubles which I can't find any solutions for. I have a model in my project which contains a method to fetch some data from MongoDB, which works just fine as long as I use findOne() instead of find().
The method:
public function getData($input) {
$output = $this->_collection->find($input);
//$output = $this->_collection->findOne($input);
Zend_Debug::Dump($output);
return $output;
}
When running that piece of code I get this from the dump:
object(MongoCursor)#52 (0) {
}
Using findOne() :
array(12) {
["_id"] => object(MongoId)#54 (1) {
["$id"] => string(24) "4fd85d178efd307080000001"
}
["autoadd"] => string(1) "1"
["name"] => string(5) "Sport"
["keyword"] => string(8) "cookie29"
["antal"] => string(1) "0"
["antal_week_date"] => string(10) "1218818007"
["version"] => string(1) "1"
["active"] => string(1) "1"
["antal_week"] => string(1) "0"
["customer_id"] => string(1) "2"
["id"] => string(2) "29"
["insert_date"] => string(10) "2007-11-21"
}
And when using $output = $this->_collection->find($input)->count();:
int(20)
What am I doing wrong? This might be a simple problem, but I can't find any other way to do this stuff. If you wonder what the input is, it's just an associative array:
$data = array('active' => '1');
Please help me fetch all those 20 nice "rows" of data.
I'd be grateful.
Thanks for your advice and better wisdom!
find() returns cursor, not the array with actual data. You have to iterate the cursor. This is an example from the documentation
$m = new Mongo();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'phpmanual');
// search for documents where 5 < x < 20
$rangeQuery = array('x' => array( '$gt' => 5, '$lt' => 20 ));
$cursor = $collection->find($rangeQuery);
foreach ($cursor as $doc) {
var_dump($doc);
}

Categories