Parse Error in PHP with MongoDB - php

I'm trying to query a mongodb database with the _id stored in a session variable...
getting the _id and store as session variable:
$_SESSION['user']['userid']=$user['_id']->{'$id'};
querying db - error on this line:
$user=collection->findOne(array('_id' => new MongoId($_SESSION['user']['userid'])));
can't figure it out.

Should be $user=$collection->findOne(array('_id' => new MongoId($_SESSION['user']['userid']))); You missed a $ infront of collection

<?php
$users= $mongo->my_db->users;
$user = $users->findOne(array('_id' => new MongoId($_SESSION['user']['userid']));
print_r($user);
?>

Related

How to refer to internal array in bson/json object?

I have bson/json data comming as an output like
{"waitedMS":0,"result":[{"_id":{"$id":"58131c7799fbad4c1d000205"},"fullname":"Deborah Cheryl Fox","firstmiddle":"Deborah Cheryl","firstlast":"Deborah Fox","student":{"_id":{"$id":"58131c7799fbad4c1d000205"},"student_id":5,"registration_temp_perm_no":"4","roll_no":4,"admission_date":"01\/07\/2016","first_name":"Deborah","middle_name":"Cheryl","last_name":"Fox","dob":"14\/09\/2000","gender":"Male","blood_group":"A+","birth_place":"R S","nationality":"Indian","language":"English","religion":"Agnostic","address_line1":"30933 Anderson Way","address_line2":"97 Lotheville Road","city":"R S","state":"Gujarat","pincode":"India","country":"India","phone1":"919039180422","phone2":"917681559405","email":"educianstudent#gmail.com","is_sms_enabled":"Yes","is_active":1,"has_finished":0,"student_category":"5","course":"58131c7099fbad4c1d0001c2","Biometric_ID":"4","siblings":"Cheryl Fox","guardian_name":"Cheryl Fox","guardian_occupation":"Data Coordiator","guardian_qualification":"Senior Quality Engineer","guardian_email_id":"educianparent#gmail.com","gaurdain_contact_details":"914519201577","guardian_relationship":"sapien","height":"4.4","weight":"44.8","allergies":"","batch":2,"academicyear":"2015","batchhistory":[{"batchid":2,"academic_year":"2015","course":"58131c7099fbad4c1d0001c2","sequenceno":1,"courseId":{"$id":"58131c7099fbad4c1d0001c2"}},{"batchid":3,"academic_year":"2016","course":"58131c7099fbad4c1d0001c2","sequenceno":2,"courseId":{"$id":"58131c7099fbad4c1d0001c2"}}],"uploads":{"profile_pic":"58131c7799fbad4c1d00020510.jpg"},"routearray":[{"routeid":2,"academicyear":"2016","current":1,"vehicleno":"JK01S8764","dateofassignment":"10\/30\/2016"}],"HostelAlloted":{"Food Preferences":"Both","Hostel":{"$id":"581647da99fbad9421000029"},"Floor":"Floor_1","RoomNumber":1,"Approved":"yes","Approved On":{"sec":1477852200,"usec":0},"Academic Year":"2016"},"HostelAllotmentHistory":[{"Food Preferences":"Both","Hostel":{"$id":"581647da99fbad9421000029"},"Floor":"Floor_1","RoomNumber":1,"Approved":"yes","Approved On":{"sec":1477852200,"usec":0},"Academic Year":"2016"}],"created_at":null,"updated_at":"","courseId":{"$id":"58131c7099fbad4c1d0001c2"}}}....
....
],"ok":1}
After writting this $cursor = $output["result"];
I am able to fetch only result like below
[{"_id":{"$id":"58131c7799fbad4c1d000205"},"fullname":"Deborah Cheryl Fox","firstmiddle":"Deborah Cheryl","firstlast":"Deborah Fox","student":{"_id":{"$id":"58131c7799fbad4c1d000205"},"student_id":5,"registration_temp_perm_no":"4","roll_no":4,"admission_date":"01\/07\/2016","first_name":"Deborah","middle_name":"Cheryl","last_name":"Fox","dob":"14\/09\/2000","gender":"Male","blood_group":"A+","birth_place":"R S","nationality":"Indian","language":"English","religion":"Agnostic","address_line1":"30933 Anderson Way","address_line2":"97 Lotheville Road","city":"R S","state":"Gujarat","pincode":"India","country":"India","phone1":"919039180422","phone2":"917681559405","email":"educianstudent#gmail.com","is_sms_enabled":"Yes","is_active":1,"has_finished":0,"student_category":"5","course":"58131c7099fbad4c1d0001c2","Biometric_ID":"4","siblings":"Cheryl Fox","guardian_name":"Cheryl Fox","guardian_occupation":"Data Coordiator","guardian_qualification":"Senior Quality Engineer","guardian_email_id":"educianparent#gmail.com","gaurdain_contact_details":"914519201577","guardian_relationship":"sapien","height":"4.4","weight":"44.8","allergies":"","batch":2,"academicyear":"2015","batchhistory":[{"batchid":2,"academic_year":"2015","course":"58131c7099fbad4c1d0001c2","sequenceno":1,"courseId":{"$id":"58131c7099fbad4c1d0001c2"}},{"batchid":3,"academic_year":"2016","course":"58131c7099fbad4c1d0001c2","sequenceno":2,"courseId":{"$id":"58131c7099fbad4c1d0001c2"}}],"uploads":{"profile_pic":"58131c7799fbad4c1d00020510.jpg"},"routearray":[{"routeid":2,"academicyear":"2016","current":1,"vehicleno":"JK01S8764","dateofassignment":"10\/30\/2016"}],"HostelAlloted":{"Food Preferences":"Both","Hostel":{"$id":"581647da99fbad9421000029"},"Floor":"Floor_1","RoomNumber":1,"Approved":"yes","Approved On":{"sec":1477852200,"usec":0},"Academic Year":"2016"},"HostelAllotmentHistory":[{"Food Preferences":"Both","Hostel":{"$id":"581647da99fbad9421000029"},"Floor":"Floor_1","RoomNumber":1,"Approved":"yes","Approved On":{"sec":1477852200,"usec":0},"Academic Year":"2016"}],"created_at":null,"updated_at":"","courseId":{"$id":"58131c7099fbad4c1d0001c2"}}},
....
....
Now i want to fetch student array only in cursor. I have written
$cursor = $output["result"]["student"].
It throws error "undefined index error message".
Try this
$cursor = $output["result"][0]['student'];
$students = array_map(function($v){return $v['student'];}, $output["result"]);

Insert data in MongoDB using PHP

I am on php 5.6 using WAMP and want to insert a document into MongoDB using PHP. I am doing it in this way:
<?php
require 'vendor/autoload.php';
$con = new MongoDB\Client("mongodb://localhost:27017");
echo "successfully";
$db = $con->selectDatabase('DB');
echo "Selected";
$col = $db->selectCollection('myCol');
$document = array(
"name" => "Deny",
"password" => "1234"
);
$col->insert($document);
echo "successfully";
?>
But it is giving the error
Fatal error: Call to undefined method MongoDB\Collection::insert() in C:\wamp64\www...
I have read http://php.net/manual/en/mongocollection.insert.php and when I use the same insert function, it doesn't work for me.
Instead of MongoDB\Client use MongoClient .
This works for me.
You have to install MongoClient library:
http://php.net/manual/en/mongo.installation.php
Instead of method MongoDB\Collection::insert() using insertOne() or insertMany() would work!

session on CodeIgniter 3, userdata or not?

I'm trying to following a youtube tuts for make a login system on CodeIgniter.
I was pretty new on php framework and I choose CI for its semplicity.
So I have an array where I need to store session data:
$data = array('email' => $this->input->post('email'),
is_logged_in' => true);
the tutorial use userdata(); function with
$this->session->userdata($data);
but when he try to print de session array do:
print_r($this->session->all_userdata($data));
alluserdata(); is deprecated, so I read the doc, and I found out that userdata is a legacy function.
I want to learn what I write so I try to modernize the code to be updated and clean for CI3.
is use userdata(); good for CI3? or I have to use $_SESSION[]? or $this->session?
The problems is that if I try to use
$this->session->data
and than:
print_r($this->session->data);
I have nothing in output.
I just want to output data array in session so I can understand if it's working.
Thank you in advance
EDIT
if i use set_userdata() for set session and just print_r($this->session->userdata()); for print session all I have is:
Array
(
[__ci_last_regenerate] => 1453313633
[email] => admin#admin.com
[is_logged_in] => 1
)
and not info about browser, time ecc...is that normal?
Set session data
$newdata = array('email' => $email, 'is_logged_in' => true);
$this->session->set_userdata($newdata);
Get session data
$email = $this->session->userdata('email');
$is_logged_in = $this->session->userdata('is_logged_in');
OR
$dataArray = $this->session->userdata();
In Codignitor 3 you can get values from $this->session obejct as:
//Normal PHP
$name = $_SESSION['name'];
// IN Ci:
$name = $this->session->name
// you can also get by
$name = $this->session->userdata('name');
And whats wrong with your code?
You are using session object as
$this->session->data
This should be
$this->session->userdata
is use userdata(); good for CI3? or I have to use _SESSION[]?
For this, yes it's better to use framework libaray becuase you can manage and reuse your code easily.

mongodb getLastError() php

how do i use getLastError() within php to check if my save method is inserting to mongo?
i set up my db as follows:
$this->databaseEngine = $app['mongo'];
$this->db = $this->databaseEngine->dbname;
$this->collection = $this->db->collectionname;
my insert query then looks like this:
$query = array(
'fieldname' => $fieldname
);
$this->collection->insert($query);
I want to then use getLastError() to check whether it is inserting correctly, and if not why. but im not sure how to implement it.
do i use after the insert:
$this->collection->getLastError("what goes here?");
cheers.
Update
i eventually used this to get the last error:
echo '<pre>' . print_r($this->databaseEngine->lastError(), true) . '</pre>';
Sammaye's way works just as well, see below.
$this->collection->getLastError("what goes here?");
Nothing goes there, the return of the getLastError is the last error from MongoDB ( http://www.php.net/manual/en/mongodb.lasterror.php ). Also it is used on the MongoDB class (atm).
You don't have to use it like that, instead you can do:
$this->collection->insert($query, ARRAY('safe' => TRUE));
This will return an array from the function detailing whether or not it actually inserted. The details of the array can be found by reading this page:
http://www.php.net/manual/en/mongocollection.insert.php

Codeigniter query does not insert

The data is being sent from the front end like this:
var data = {
'user_id':userid,
'qid':array[qnum].qid,
'user_ans':userAnswers[qnum].answer,
'user_time':userTime,
'exerciseid':exid,
'point_scored':points
};
$.post('<?php echo base_url()?>main/update_user_score',
{ myData : data },
function(result){} );
And in my "main" controller, I have:
$post_data = $_POST['myData'];
$data = array(
'user_id' => $post_data[user_id] ,
'qid' => $post_data[qid],
'user_ans' => $post_data[user_ans],
'user_time' => $post_data[user_time],
'exerciseid' => $post_data[exerciseid],
'point_scored' => $post_data[point_scored]
);
$this->load->model('Question_model','questions');
$this->questions->update_user_attempt($data);
In my Question_model / update_user_attempt:
error_log("data in model BEFORE INSERT:" . json_encode($data));
$this->db->insert('user_attempt', $data);
error_log("data in model AFTER INSERT: ");
The problem is, the data reaches (at least seems to me) the model quite fine. Here's the log entry:
[23-Apr-2012 16:04:47] data in model BEFORE INSERT:{"user_id":"5","qid":"3","user_ans":"d","user_time":"3","exerciseid":"cr1","point_scored":"35"}
BUT there is NO "after insert" log entry. The insert itself does not happen, and neither does the log entry after the insert.
I can read from the DB quite fine. So I checked in phpmyadmin the user privileges of the user in "config/database.php", and that user has ALL privileges, including INSERT.
So two questions:
What is the problem? What mistake am I making?
How do I even begin finding out what is going on with the insert statement? (I cannot find anything in the logs.)
I am looking at xampp/apache/logs/error.log and xampp/php/logs/php_error_log. Should I be looking at some other logs?
Try putting $this->db->_error_message(); after db insert
like this ...
error_log("data in model BEFORE INSERT:" . json_encode($data));
$this->db->insert('user_attempt', $data);
echo $this->db->_error_message();
error_log("data in model AFTER INSERT: ");
Aren't you missing this
$post_data['user_id']
Instead you are using without quotes
Don't forget to use $this->db->last_query() after your insert statement to see what the insert statement looks like. copy and paste that insert statement into your sql client to see if the query is actually working on its own.
Try adding
ini_set("display_errors", "1");
Also before your insert,
var_dump($data); die();
to see exactly what you are passing. Then check here to see that you are properly forming the insert statment.
First thing I thought was: shouldn't you use json_decode in stead of json_encode?
Did you set error_reporting(E_ALL);?

Categories