Fatal error: Call to a member function selectCollection() on a non-object in \lib\dbconnection.php on line 55 - mongodb

<?php
class DBConnection {
const HOST = 'localhost';
const PORT = 27017;
const DBNAME = 'lib';
private static $instance;
public $connection;
public $database;
private function _construct()
{
$connectionString = sprintf('mongodb://%s:%d', DBConnection::HOST, DBConnection::PORT);
try {
$this->connection = new Mongo($connectionString); $this->database = $this->connection-> selectDB(DBConnection::DBNAME);
} catch (MongoConnectionException $e) {
throw $e;
}
}
static public function instantiate()
{
if (!isset(self::$instance)) {
$class = __CLASS__;
self::$instance = new $class;
}
return self::$instance;
}
public function getCollection($name)
{
return $this->database->selectCollection($name);
}
}
help pleaseee

You have a typo: __construct has two _'s, and you only have one.

Related

Issue with add global variable codeigniter 3

I've admin dashboard with header available in all pages.
in Admin Controller I add function:
`class Admin_controller extends Admin_Core_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$data['notification_count'] = $this->order_admin_model->get_all_notifications_count();
$data['notification'] = $this->order_admin_model->get_all_notifications();
$this->load->view('admin/includes/_header', $data);
$this->load->view('admin/index');
$this->load->view('admin/includes/_footer');
}
}`
The problem is this working only for "home page (index)" dashboard. When I open anyother page then I get issue undefinied variable.
How can I call this variables in global?
`
$data['notification_count'] = $this->order_admin_model->get_all_notifications_count();
$data['notification'] = $this->order_admin_model->get_all_notifications();`
update:
I've one file Core_Controller.php and this file contains:
class Admin_Core_Controller extends Core_Controller
{
public function __construct()
{
parent::__construct();
if (!is_admin()) {
redirect(admin_url() . 'login');
exit();
}
//set control panel lang
$this->control_panel_lang = $this->selected_lang;
if (!empty($this->session->userdata('mds_control_panel_lang'))) {
$this->control_panel_lang = $this->session->userdata('mds_control_panel_lang');
//language translations
$this->language_translations = $this->get_translation_array($this->control_panel_lang->id);
}
//check long cron
if (check_cron_time_long() == true) {
//delete old sessions
$this->settings_model->delete_old_sessions();
//add last update
$this->db->where('id', 1)->update('general_settings', ['last_cron_update_long' => date('Y-m-d H:i:s')]);
}
}
protected function render($view, $data = NULL)
{
$data['notification_count'] = $this->order_admin_model->get_all_notifications_count();
$data['notification'] = $this->order_admin_model->get_all_notifications();
$this->load->view('admin/includes/_header', $data);
$this->load->view($view, $data);
$this->load->view('admin/includes/_footer');
}
public function paginate($url, $total_rows)
{
//initialize pagination
$page = $this->security->xss_clean($this->input->get('page'));
$per_page = $this->input->get('show', true);
$page = clean_number($page);
if (empty($page) || $page <= 0) {
$page = 0;
}
if ($page != 0) {
$page = $page - 1;
}
if (empty($per_page)) {
$per_page = 15;
}
$config['num_links'] = 4;
$config['base_url'] = $url;
$config['total_rows'] = $total_rows;
$config['per_page'] = $per_page;
$config['reuse_query_string'] = true;
$this->pagination->initialize($config);
return array('per_page' => $per_page, 'offset' => $page * $per_page);
}
}
You see I add your code here and now in Admin_Controller I add:
class Admin_controller extends Admin_Core_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$data['title'] = trans("admin_panel");
$data['order_count'] = $this->order_admin_model->get_all_orders_count();
$data['product_count'] = $this->product_admin_model->get_products_count();
$data['pending_product_count'] = $this->product_admin_model->get_pending_products_count();
$data['blog_posts_count'] = $this->blog_model->get_all_posts_count();
$data['members_count'] = $this->auth_model->get_users_count_by_role('member');
$data['latest_orders'] = $this->order_admin_model->get_orders_limited(15);
$data['latest_pending_products'] = $this->product_admin_model->get_latest_pending_products(15);
$data['latest_products'] = $this->product_admin_model->get_latest_products(15);
$data['latest_reviews'] = $this->review_model->get_latest_reviews(15);
$data['latest_comments'] = $this->comment_model->get_latest_comments(15);
$data['latest_members'] = $this->auth_model->get_latest_members(6);
$data['latest_transactions'] = $this->transaction_model->get_transactions_limited(15);
$data['latest_promoted_transactions'] = $this->transaction_model->get_promoted_transactions_limited(15);
$this->load->view('admin/includes/_header', $data);
$this->render('admin/index');
$this->load->view('admin/includes/_footer');
}
and after this dashboard now working and everytime is refreshed every sec.
I would suggest creating a base controller with a render function, then have your controllers extend from this base controller and use this function to render their pages. The render function can then contain the variables that need to be available on all pages.
Since you already have an Admin_Core_Controller class, you might be able to add the render function there instead (not sure of your project structure). Something like this:
class Admin_Core_Controller // ...
{
// ...
protected function render($view, $data = NULL)
{
$data['notification_count'] = $this->order_admin_model->get_all_notifications_count();
$data['notification'] = $this->order_admin_model->get_all_notifications();
$this->load->view('admin/includes/_header', $data);
$this->load->view($view, $data);
$this->load->view('admin/includes/_footer');
}
}
Then use it to render your page in Admin_Controller:
class Admin_controller extends Admin_Core_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->render('admin/index');
}
}
Edit Your Admin_Controller class should look like this - I've removed the header and footer includes (those are already rendered by the render function) and passed the $data array to render:
class Admin_controller extends Admin_Core_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$data['title'] = trans("admin_panel");
$data['order_count'] = $this->order_admin_model->get_all_orders_count();
$data['product_count'] = $this->product_admin_model->get_products_count();
$data['pending_product_count'] = $this->product_admin_model->get_pending_products_count();
$data['blog_posts_count'] = $this->blog_model->get_all_posts_count();
$data['members_count'] = $this->auth_model->get_users_count_by_role('member');
$data['latest_orders'] = $this->order_admin_model->get_orders_limited(15);
$data['latest_pending_products'] = $this->product_admin_model->get_latest_pending_products(15);
$data['latest_products'] = $this->product_admin_model->get_latest_products(15);
$data['latest_reviews'] = $this->review_model->get_latest_reviews(15);
$data['latest_comments'] = $this->comment_model->get_latest_comments(15);
$data['latest_members'] = $this->auth_model->get_latest_members(6);
$data['latest_transactions'] = $this->transaction_model->get_transactions_limited(15);
$data['latest_promoted_transactions'] = $this->transaction_model->get_promoted_transactions_limited(15);
$this->render('admin/index', $data);
}
}

How to do queries with pdo db connection function?

I read too many questions and answers around but couldn't be sure.
I have 2 questions
1.I turned my db connection into a function and I am not sure if its
safe ?
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'demo');
function DB()
{
try {
$pdo = new PDO('mysql:host='.DB_SERVER.';dbname='.DB_NAME.'', DB_USERNAME, DB_PASSWORD);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
} catch (PDOException $e) {
return "Error!: " . $e->getMessage();
die();
}
}
2.is my query done right way ?
query:
try {
$pdo = DB();
$stmt = $pdo->prepare("SELECT * FROM settings");
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$c = htmlspecialchars($row['site_url']);
$e = filterString($row['contact']);
}
unset($stmt);
} catch (PDOException $e) {
exit($e->getMessage());
}
Thanks for any help
Perhaps keep one connection, rather than opening multiple connections to the Database. You can look into a project PDOEasy that I created to make MVC easy with PDO or use the below static example.
class DB
{
private $_connection;
private static $_instance;
public static function getInstance() {
if(self::$_instance) return self::$_instance;
self::$_instance = new self();
return self::$_instance;
}
private function __construct() {
$this->_connection = new PDO('mysql:host='.DB_SERVER.';dbname='.DB_NAME.'', DB_USERNAME, DB_PASSWORD, array(
PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
));
}
public function getConnection() { return $this->_connection; }
}
Which can be used like so:
$stmt = DB::getInstance()
->getConnection()
->Prepare('SELECT * FROM settings');
$stmt->execute();
foreach($stmt->fetchAll() as $row) {
// ...
}

Zend Framewok not populating all table field's value

I'm beginner for Zend Framework and using Zend Framework 2.5 veresion. I'm getting same issue and can't be resolved.My Model.php is different than show above.
Model.php
namespace User;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
class Module implements AutoloaderProviderInterface, ConfigProviderInterface{
public function getAutoloaderConfig(){
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__.'/src/'.__NAMESPACE__,
)
)
);
}
public function getConfig(){
return include __DIR__. '/config/module.config.php';
}
}
My 'tbl_user' has fields with '_' like 'first_name', 'last_name', 'contact_num' which are not listing. other without underscore '_' fields are listing.
What is wrong with me, can anyone help me?
My output is:
User\Model\User Object
(
[id:protected] => 4
[first_name:protected] =>
[last_name:protected] =>
[contact_num:protected] =>
[email:protected] => dev#email.com
[designation:protected] => C++Programmer
[text:protected] =>
[name:protected] =>
[profile_pic:protected] =>
)
here is my Model 'User.php'
<?php
namespace User\Model;
class User implements UserInterface{
protected $id;
protected $first_name;
protected $last_name;
protected $contact_num;
protected $email;
protected $designation;
protected $text;
protected $name;
protected $profile_pic;
public function getId(){
return $this->id;
}
public function setId($id){
$this->id = $id;
}
public function getName(){
return $this->name;
}
public function setName($first_name, $last_name){
$this->name = $first_name.' '.$last_name;
}
public function getContact(){
return $this->contact_num;
}
public function setContact($contact_num){
$this->contact_num = $contact_num;
}
public function getEmail(){
return $this->email;
}
public function setEmail($email){
$this->email = $email;
}
public function getDesignation(){
return $this->designation;
}
public function setDesignation($designation){
$this->designation = $designation;
}
public function getProfilePic(){
return $this->profile_pic;
}
public function setProfilePic($profile_pic){
$this->profile_pic = $profile_pic;
}
/*public function getText(){
return $this->text;
}
public function setText($text){
$this->text = $text;
}*/
}
?>
and this is my 'ZendDbSqlMapper.php'
<?php
namespace User\Mapper;
use User\Model\UserInterface;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Db\Adapter\Driver\ResultInterface;
use Zend\Db\ResultSet\HydratingResultSet;
use Zend\Stdlib\Hydrator\HydratorInterface;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Insert;
use Zend\Db\Sql\Update;
class ZendDbSqlMapper implements UserMapperInterface{
protected $dbAdapter;
protected $hydrator;
protected $userPrototype;
public function __construct(
AdapterInterface $dbAdapter,
HydratorInterface $hydrator,
UserInterface $userPrototype
){
$this->dbAdapter = $dbAdapter;
$this->hydrator = $hydrator;
$this->userPrototype = $userPrototype;
}
public function find($id){
$sql = new Sql($this->dbAdapter);
$select = $sql->select('tbl_users');
$select->where(array('id = ?' => $id));
$stmt = $sql->prepareStatementForSqlObject($select);
$result = $stmt->execute();
if($result instanceof ResultInterface && $result->isQueryResult() && $result->getAffectedRows()){
return $this->hydrator->hydrate($result->current(), $this->userPrototype);
}
throw new \InvalidArgumentException("User with given ID:{$id} not found");
}
public function findAll(){
$sql = new Sql($this->dbAdapter);
$select = $sql->select('tbl_users');
$stmt = $sql->prepareStatementForSqlObject($select);
$result = $stmt->execute();
//\Zend\Debug\Debug::dump($result); die;
if($result instanceof ResultInterface && $result->isQueryResult()){
//$resultSet = new ResultSet();
$resultSet = new HydratingResultSet($this->hydrator, $this->userPrototype);
//\Zend\Debug\Debug::dump($resultSet->initialize($result)); die;
return $resultSet->initialize($result);
}
return array();
}
public function save(UserInterface $userObject){
$userData = $this->hydrator->extract($userObject);
unset($userData['id']);
if($userObject->getId()){
$action = new Update('tbl_users');
$action->setData($userData);
$action->where(array('id = ?' => $userObject->getId()));
}else{
$action = new Insert('tbl_users');
$action->values($userData);
}
$sql = new Sql($this->dbAdapter);
$stmt = $sql->prepareStatementForSqlObject($action);
$result = $stmt->execute();
if($result instanceof ResultInterface){
if($newId = $result->getGeneratedValue()){
$userObject->setId($newId);
}
return $userObject;
}
return new \Exception("Database Error");
}
}
?>
here is 'ListController.php'
<?php
namespace User\Controller;
use User\Service\UserServiceInterface;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class ListController extends AbstractActionController{
protected $userService;
public function __construct(UserServiceInterface $userService){
$this->userService = $userService;
}
public function indexAction(){
return new ViewModel(array(
'users' => $this->userService->findAllUsers()
));
}
public function detailAction(){
$id = $this->params()->fromRoute('id');
try {
$user = $this->userService->findUser($id);
}catch(\InvalidArgumentException $ex){
return $this->redirect()->toRoute('user');
}
return new ViewModel(
array( 'user' =>$user )
);
}
}
?>
thank you.

Call to a member function allow() on a non-object - authorization

I used this tutorial: http://book.cakephp.org/2.0/en/tutorials-and-examples/blog-auth-example/auth.html
To build my first form/create user app, but it fails with an error message:
Fatal error: Call to a member function allow() on a non-object in /home/public_html/cake/app/Controller/UsersController.php on line 18
This ius the 18 line:
$this->Auth->allow('add', 'logout');
The above line is a member of function:
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add', 'logout');
}
My whole UsersController.php:
<?php
class UsersController extends AppController {
public function login() {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
public function logout() {
$this->redirect($this->Auth->logout());
}
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add', 'logout');
}
public function index() {
$this->User->recursive = 0;
$this->set('users', $this->paginate());
}
public function view($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
$this->set('user', $this->User->read(null, $id));
}
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
public function edit($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$this->request->data = $this->User->read(null, $id);
unset($this->request->data['User']['password']);
}
}
public function delete($id = null) {
if (!$this->request->is('post')) {
throw new MethodNotAllowedException();
}
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->User->delete()) {
$this->Session->setFlash(__('User deleted'));
$this->redirect(array('action'=>'index'));
}
$this->Session->setFlash(__('User was not deleted'));
$this->redirect(array('action' => 'index'));
}
}
?>
Why does it happends?
Make sure the Auth compenent is actually called in your AppController. If you don't have an AppController create AppController.php in your Controllers directory with the following code:
<?php
class AppController extends Controller {
}
?>
The Auth component is called in a public variable in the AppController, so the controller would look like this:
<?php
class AppController extends Controller {
public $components = array('Auth');
}
?>
Auth is now available throughout your application. You could also call the AuthComponent in your UsersController, but that would make it only available to that particular controller. You probably want to use authentication in your entire application.

Parse error: syntax error, unexpected $end, expecting T_FUNCTION in ClmsRegistrationModel.php

<?php
/**
* clmsRegistration
*
* #author MGUCS-07
* #version
*/
require_once 'Zend/Db/Table/Abstract.php';
class ClmsRegistrationModel extends Zend_Db_Table_Abstract
{
/**
* The default table name
*/
protected $_name = "clms_registration";
protected $_primary = "user_name";
public static function changePassword($username, $newpassword)
{ //changes the password
try {
$chps= new ClmsRegistrationModel();
$row = $chps->find($username);
$row1 = $row->current();
$row1->password=$newpassword;
$row1->save();
}
catch (Zend_Db_Exception $e)
{
$e->getMessage();
}
}
public static function checkUsed($username)
{ //check whether used or not
try {
$table = new ClmsRegistrationModel();
$row=$table->find($username);
if($row)
{
return 1;
}}
catch (Zend_Db_Exception $e)
{
$e->getMessage();
}
}
public static function deleteUser($user_name)
{ //deletes a user
try {
$deluser=new ClmsRegistrationModel();
$row = $deluser->find($user_name);
$row1=$row->current();
$result = $row1->delete();
}
catch (Zend_Db_Exception $e)
{
$e->getMessage();
}
}
public static function updateUser($user_name,$district,$email_id,$phone_number)
{
//updates the details of the user
try {
$upUser = new ClmsRegistrationModel();
$row = $upUser->find($user_name);
$row1=$row->current();
$row1->district= $district;
$row1->email_id= $email_id;
$row1->phone_number= $phone_number;
$row1->save();
}
catch (Zend_Db_Exception $e)
{
$e->getMessage();
}
}
public static function getRole($user_name)
{ //gets the role of the user
try {
$roq= new ClmsRegistrationModel();
$u= $roq->fetchRow($roq->select()->where('user_name=?',$user_name));
return $u->toArray();
}
catch (Zend_Db_Exception $e)
{
$e->getMessage();
}
}
public function isActive($user_name)
{ //select active user
try {
$roq = new ClmsRegistrationModel();
$u= $roq->fetchRow($roq->select()->where('user_name=?',$user_name));
return $u->toArray();
}
catch (Zend_Db_Exception $e)
{
$e->getMessage();
}
}
public function setActive($user_nam)
{ //sets user active
try {
$roq = new ClmsRegistrationModel();
$row= $roq->find($user_nam);
$row1=$row->current();
$row1->user_name= $user_nam;
$row1->status1 = 1;
$row1->save();
}
catch (Zend_Db_Exception $e)
{
$e->getMessage();
}
}
public static function setRole($user_name,$role)
{ //sets the role of the user
try {
$reg=new ClmsRegistrationModel();
$row = $reg->find($user_name);
$row1= $row->current();
$row1->role_organization=$role;
$row1->save();
}
catch (Zend_Db_Exception $e)
{
$e->getMessage();
}
}
public function register($uname,$pass,$role,$en,$status,$email,$ph,$date,$dis)
{// function for registration purposes
try{
$reg = new ClmsRegistrationModel();
$row =$reg->fetchNew();
//$row= $row->current();
$row->user_name = '$uname';
$row->password = '$pass';
$row->role = $role;
$row->employee_name=$en;
$row->status1=$status;
$row->email_id =$email;
$row->phone_number =$ph;
$row->date =$date;
$row->District=$dis;
$row->employe_id =$row->employe_id +1;
$row->save();
//$reg->save();
}
catch (Zend_Db_Exception $e){
$e->getMessage();
}
}
}
This is my model class and getting that error.
Please tell why this error and how to debug it.
well neither of those are correct answers. there are 2 braces in if statement
if($row)
{
return 1;
}}
try this
$reg = new ClmsRegistrationModel();
$row1 =$reg->createRow();
$row1->user_name = $uname;
$row1->password= $pass;
$row1->role = $role;
$row1->employee_name=$en;
$row1->status1=$status;
$row1->email_id =$email;
$row1->phone_number =$ph;
$row1->date =$date;
$row1->District=$dis;
$row1->save();
remove public from line 1 then try again