MongoDB insertOne function not found - php

I'm trying to use MONGODB in my project and I just started using it when it has this problem. I created another directory and ran the files with no problems whatsoever. What is wrong with this? I keep getting Fatal error: Uncaught Error: Call to undefined method MongoDB\Database::insertOne() error message.
This is my code to the class called Database which is producing the error.
<?php
namespace auth;
include_once dirname(__DIR__) . "/config.php";
class Database
{
public function __construct(
private readonly string $dbname,
){
$this->run();
}
private function run(): void
{
$collection = (new \MongoDB\Client)->{$this->dbname};
$insertOneResult = $collection->insertOne([
'username' => 'admin',
'email' => 'admin#example.com',
'name' => 'Admin User',
]);
printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount());
var_dump($insertOneResult->getInsertedId());
}
}
and my test.php file just contained some lines of code
include_once "./assets/php/config.php";
$database = new \auth\Database("test->users");
I definitely loaded the class MongoDB and my config.php includes the vendor file of composer's.
This is the error in full.
Fatal error: Uncaught Error: Call to undefined method MongoDB\Database::insertOne() in C:\xampp\htdocs\PP\assets\php\Classes\Database.php:18
Stack trace:
#0 C:\xampp\htdocs\PP\assets\php\Classes\Database.php(11): auth\Database->run()
#1 C:\xampp\htdocs\PP\test.php(15): auth\Database->__construct('test->users')
#2 {main}
thrown in C:\xampp\htdocs\PP\assets\php\Classes\Database.php on line 18
PHP Fatal error: Uncaught Error: Call to undefined method MongoDB\Database::insertOne() in C:\xampp\htdocs\PPa\assets\php\Classes\Database.php:18
Stack trace:
#0 C:\xampp\htdocs\PP\assets\php\Classes\Database.php(11): auth\Database->run()
#1 C:\xampp\htdocs\PP\test.php(15): auth\Database->__construct('test->users')
#2 {main}
thrown in C:\xampp\htdocs\PP\assets\php\Classes\Database.php on line 18
Process finished with exit code 255
The config.phpfile that I have included
include_once dirname(__DIR__, 2) . "/vendor/autoload.php";
include_once "autoload.php";
Thanks for any help.

Ah yes answer to my question, I'm just well not thinking properly at the time of writing the code. The `MongoDB\Collection" class accepts two arguments from the user and one internally set. The user provided argument is the database name and collection name. Doing it with (new \MongoDB\Client)->{$this->dbname} is wrong because it provides just the database string and not the collection name.
I resolved this issue by changing how the structure looks of the collection. md is just the alias for MongoDB class as I do not want to type such a long string everytime.
$collection = (new md\Client)->$db->$collection_name;
However, I have no idea how mongoDB uses the db and collection_name as magic constants as I have looked through the entire MongoDB\Client file and found there is no code stating those "magic constants"? I would appreciate if someone has an answer to this.

Related

How to access/read files/pages on webside

in my case I get this error massage
Fatal error: Uncaught Error: Class "RandomClass" not found in /webspace/projectfolder/pages/add_eventuser.php:10 Stack trace: #0 {main} thrown in /webspace/projectfolder/pages/add_eventuser.php on line 10
I use
$_SERVER['DOCUMENT_ROOT']
to get the exact path of the file
In my structure i organized the files like this:
projectfolder/includes/class.php where the pointed class should loaded
projectfolder/pages/initiatorpage.php where i got the Fatal Error
public class DatabaseColums
{
public function loadDatabase($databaseName)
{
$databaseName = "test";
return $databaseName;
}
}
include $_SERVER['DOCUMENT_ROOT'].'includes/RandomClass.php';
$dbinput = new DatabaseColums();
echo $dbinput->loadDatabase();
I made the folder/file restrictions read/write/executeable
Cant explain to myself why I got still this massage.
What Issue is behind that.
Thank you for your attention
the problem was a missing / between $_SERVER['DOCUMENT_ROOT'] and /folder/file.php
--right :$_SERVER['DOCUMENT_ROOT']./ folder/file.php
--wrong: $_SERVER['DOCUMENT_ROOT'].folder/file.php
Thank you #Ajmal Praveen and
#ADyson

Fatal error: Uncaught Error: Call to undefined function that is not in a class

So i am working on some code and have come across this error and its starting to bug me a little as i cant find out what is wrong
i have 2 files main.php and that includes functions.php now in the main file i have the following code
<?php
include "functions.php";
$NAME = GET_USER_NAME();
?>
That is all thats in the main file now in the functions file i have the following code
<?php
function GET_USER_NAME() {
return 'bob';
}
function GET_USER_AGE() {
return '5';
}
?>
now when i try and open main in my browser i get the error
Fatal error: Uncaught Error: Call to undefined function GET_USER_NAME() in /var/www/html/main.php:3 Stack trace: #0 {main} thrown in /var/www/html/main.php on line 3
i know the file is being included properly as i can run the function
GET_USER_AGE();
from the main file and it returns 5
The only possible solutions to your problem are :
A typo in the function called in the main, which is not the exact same as in your included file (case sensitivity ?)
The include references a file which is not the one you want (but has one of the 2 desired functions)
And also yes, as #Markus-Zeller says, don't use method names like that, as stated here : https://www.php-fig.org/psr/psr-1/#1-overview

use of class with namespace error

in api.php i use severall classes, with autoloaders. in include them like this
use \protoware\cms\Account as Account;
use \protoware\cms\Content as Content;
use protoware\cms\Count as Count;
include __DIR__ . '/vendor/autoload.php';
Local this works fine, when i upload it on a server i get this
Europe/Brussels] PHP Fatal error: Uncaught Error: Class 'protoware\cms\Content' not found in /data/vhosts/achielvolckaert.be/wwwroot/api.php:97
Stack trace:
#0 {main}
thrown in /data/vhosts/achielvolckaert.be/wwwroot/api.php on line 97
line 97 is the first line where i open a connection:
$content = new protoware\cms\Content();
$data = $content->get_content('medisch');
I have 0 clue how to fix this, i updated autloader, checked if all files were uploaded...
Try add a \ before class name, like $content = new \protoware\cms\Content(); or just $content = new Content() since you have a use statement.
If this class is a dependency, check if its correctly installed (inside your vendor folder, i.e.). Maybe run composer install?

SmartyBC (Backwards Compatibility Wrapper) doesn't work in PrestaShop

As adviced in Smarty's instruction, in order to use deprecated functions like include_php in newest PrestaShop, I had to switch from Smarty.class.php to SmartyBC.class.php. I did it by modyfing in smarty.config.inc.php following lines:
require_once(_PS_SMARTY_DIR_.'SmartyBC.class.php');
// require_once(_PS_SMARTY_DIR_.'Smarty.class.php');
global $smarty;
// $smarty = new Smarty();
$smarty = new SmartyBC();
However, using {include_php file='./custom_php/manufacturers.php'} in theme's header.tpl still results in blank screen. Errors from php_error_log :
[22-Jul-2014 15:05:55 Europe/Warsaw] PHP Notice: Undefined property: SmartyBC::$trusted_dir in C:\BACKUP\Dropbox\!_PC\LOCALHOST\_INTERCLICK\trzmiel5\tools\smarty\Smarty.class.php on line 676
[22-Jul-2014 15:05:55 Europe/Warsaw] PHP Fatal error: Uncaught exception 'SmartyCompilerException' with message 'Syntax Error in template "C:\BACKUP\Dropbox\!_PC\LOCALHOST\_INTERCLICK\trzmiel5\themes\trzmiel\header.tpl" on line 101 "{include_php file='./custom_php/manufacturers.php'}" {include_php} file './custom_php/manufacturers.php' is not readable' in C:\BACKUP\Dropbox\!_PC\LOCALHOST\_INTERCLICK\trzmiel5\tools\smarty\sysplugins\smarty_internal_templatecompilerbase.php:667
Stack trace:
#0 C:\BACKUP\Dropbox\!_PC\LOCALHOST\_INTERCLICK\trzmiel5\tools\smarty\sysplugins\smarty_internal_compile_include_php.php(81): Smarty_Internal_TemplateCompilerBase->trigger_template_error('{include_php} f...', 101)
#1 C:\BACKUP\Dropbox\!_PC\LOCALHOST\_INTERCLICK\trzmiel5\tools\smarty\sysplugins\smarty_internal_templatecompilerbase.php(485): Smarty_Internal_Compile_Include_Php->compile(Array, Object(Smarty_Internal_SmartyTemplateCompiler), Array, NULL, NULL)
#2 C:\BACKUP\Dropbox\!_PC\LOCALHOST\_INTERCLICK\trzmiel5\tools\smarty\sysplugins\smarty_internal_templ in C:\BACKUP\Dropbox\!_PC\LOCALHOST\_INTERCLICK\trzmiel5\tools\smarty\sysplugins\smarty_internal_templatecompilerbase.php on line 667
It seems that trusted_dir property is available only when using Security Policy:
class My_Security_Policy extends Smarty_Security {
public $trusted_dir = './custom_php/';
}
$smarty = new SmartyBC();
// enable security
$smartyBC->enableSecurity('My_Security_Policy');
so you should provide here correct path (I don't know is it relative or not - you should give a try) and then you should be able to use manufacturers.php file in your template file but you should also here look at correct file path.

'Zend_Db_Statement_Exception' with message 'Invalid bind-variable name ':1'

Good day,
Background Info:
Client's hosting server is being upgraded from PHP 5.2 to PHP 5.3. The client's app breaks when tested on PHP 5.3. Specifically the insert and update methods are the ones which are breaking the app. The app coded in Zend Framework v1.7.2.
We have tried simply upgrading the Zend Framework core, however it seems that the previous developers made changes to the core, which causes the app to completely break when the framework has been upgraded.
Problem
The best solution was to add a class called AppModel which extends Zend_Db_Table_Abstract and then simply overwrite the insert and update methods. All models in this app extend the AppModel class. This works fine until checkbox data or radio button data has to be written to the database.
The app now throws the following error:
Fatal error: Uncaught exception 'Zend_Db_Statement_Exception' with
message 'Invalid bind-variable name ':1'' in ....
NB. Full error message at the bottom
I have been looking for a solution on the internet for days in vain. One of the solutions I found was to change Mysqli to Pdo_Mysql. however it seems that there is no such class in the framework. There is the class Pdo which throws the same error as Mysqli.
Please help!
Please excuse my English. If you need clarification please dont hesitate to contact me. thanks in advance
The following is code sample from the AppModel class:
class AppModel extends Zend_Db_Table_Abstract{
//PHP 5.3 fix
public function insert(array $data) {
//array to carry data for holding data
$ins_data = array();
foreach($data as $table => $value){
$ins_data['tables'][] = $table;
$ins_data['values'][] = mysql_escape_string($value);
}
$db = Zend_Registry::get('db');
$ins_query = ' INSERT INTO '. $this->_name.' ('.implode($ins_data['tables'], ', ').')
VALUES ("'.implode($ins_data['values'], '", "').'")';
$ins_action = new Zend_Db_Statement_Mysqli($db, $ins_query);
$ins_action->execute();
return $db->lastInsertId();
}
}
Complete error message:
Fatal error:
Uncaught exception 'Zend_Db_Statement_Exception'
with message 'Invalid bind-variable name ':1''
in C:\wamp\www\schoolnet\public_html\Zend\Db\Statement.php:143
Stack trace:
#0 C:\wamp\www\schoolnet\public_html\Zend\Db\Statement.php(108): Zend_Db_Statement->_parseParameters(' UPDATE user_te...')
#1 C:\wamp\www\schoolnet\application\AppModel.php(43): Zend_Db_Statement->__construct(Object(Zend_Db_Adapter_Mysqli), ' UPDATE user_te...')
#2 C:\wamp\www\schoolnet\application\modules\user\helpers\UserHelper.php(530): AppModel->update(Array, 'user_id = 6')
#3 C:\wamp\www\schoolnet\application\modules\user\controllers\UserController.php(533): user_helpers_UserHelper->teacherUpdate(Array, 6)
#4 C:\wamp\www\schoolnet\application\modules\user\controllers\UserController.php(300): UserController->teacherUpdateDetails(Array, 6)
#5 C:\wamp\www\schoolnet\public_html\Zend\Controller\Action.php(503): UserController->detailseditAction()
#6 C:\wamp\www\schoolnet\public_html\Zend\Controller\Dispatcher\Standard.php(285): Zend_Control in C:\wamp\www\schoolnet\public_html\Zend\Db\Statement.php on line 143

Categories