I am getting the following error when running the app in xampp with Php 7. I am new to mongoDb. Can't figure out what might solve this issue. Any help or suggestion about the problem will be highly appreciated. Thank you for your help. Below is the code I believe have some issue.
Error:
An uncaught Exception was encountered
Type: Error
Message: Class 'MongoClient' not found
Filename: C:\xampp\htdocs\Web\application\libraries\Mongo_db.php
Line Number: 49
Backtrace:
File: C:\xampp\htdocs\Web\application\controllers\Home.php Line: 7
Function: __construct
File: C:\xampp\htdocs\Web\index.php Line: 315 Function: require_once
libraries\Mongo_db.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Mongo_db
{
private $debug;
private $write_concerns;
private $journal;
private $selects = array();
private $updates = array();
private $wheres = array();
private $limit = 999999;
private $offset = 0;
private $sorts = array();
private $return_as = 'array';
public $benchmark = array();
public function __construct()
{
//Check mongodb is installed in your server otherwise display an error
/*if ( ! class_exists('Mongo') && ! class_exists('MongoClient'))
{
show_error("The MongoDB PECL extension has not been installed or enabled", 500);
}*/
if (!class_exists('MongoDB\Driver\Manager')) {
show_error("The MongoDB PECL extension has not been installed or enabled", 500);
}
//get instance of CI class
if (function_exists('get_instance'))
{
$this->_ci = get_instance();
}
else
{
$this->_ci = NULL;
}
//load the config file which we have created in 'config' directory
$this->_ci->load->config('mongodb');
$config='default';
// Fetch Mongo server and database configuration from config file which we have created in 'config' directory
$config_data = $this->_ci->config->item($config);
try{
//connect to the mongodb server
$this->mb = new MongoClient('mongodb://'.$config_data['mongo_hostbase']);
//select the mongodb database
$this->db=$this->mb->selectDB($config_data['mongo_database']);
}
catch (MongoConnectionException $exception)
{
//if mongodb is not connect, then display the error
show_error('Unable to connect to Database', 500);
}
}
/**
* --------------------------------------------------------------------------------
* Aggregation Operation
* --------------------------------------------------------------------------------
*
* Perform aggregation on mongodb collection
*
* #usage : $this->mongo_db->aggregate('foo', $ops = array());
*/
public function aggregate($collection, $operation)
{
if (empty($collection))
{
show_error("In order to retreive documents from MongoDB, a collection name must be passed", 500);
}
if (empty($operation) && !is_array($operation))
{
show_error("Operation must be an array to perform aggregate.", 500);
}
try
{
$documents = $this->db->{$collection}->aggregate($operation);
//$this->_clear();
if ($this->return_as == 'object')
{
return (object)$documents;
}
else
{
return $documents;
}
}
catch (MongoResultException $e)
{
if(isset($this->debug) == TRUE && $this->debug == TRUE)
{
show_error("Aggregation operation failed: {$e->getMessage()}", 500);
}
else
{
show_error("Aggregation operation failed: {$e->getMessage()}", 500);
}
}
}
}
?>
config/mongodb.php
<?php
//mongodb host
$config['default']['mongo_hostbase'] = 'localhost';
//mongodb name
$config['default']['mongo_database'] = 'appname';
//mongodb username - by default, it is empty
$config['default']['mongo_username'] = 'root';
//mongodb password - by default, it is empty
$config['default']['mongo_password'] = 'root';
?>
config/mongo.php
<?php
$config['mongo_server'] = 'localhost:27017';
$config['mongo_dbname'] = 'appname';
?>
The MongoCLient class was provided by pecl install mongo. But pecl/mongo is not available for php7 and deprecated in favor of pecl/mongodb. But with pecl/mongodb you'll need to use MongoDB\Driver\Manager instead of MongoClient
Please see here for further reading.
Once you install MongoDB you cannot connect with PHP directly. You need to install the MongoDB Driver for PHP which you can find in the following URL
http://php.net/manual/en/mongodb.installation.php
Based on the type of the OS you can download the one.
Once your done with that. You can use the composer to download the mongo library so that you can start interacting with it
{
"require": {
"mongodb/mongodb": "^1.1"
}
}
Once your done with that you will have a vendor directory in your project folder which contains the autoload.php which will handle auto loading of the necessary and dependency libraries required in Vendor.
You can start using the library as follows
db_connect.php
<?php
/* Require the Vendor for autoloading MongoDb Client */
include_once 'vendor/autoload.php';
/* Create the Object of Mongodb */
$mongoDB = new MongoDB\Client;
/* Creating the database on which I will be working */
$erpDB = $mongoDB->database_name;
You can use the above code as follows
products.php
<?php
include_once 'DB/db_connect.php';
/* The following creates the products collection */
$productsCollection = $erpDB->products;
$insertedData = $productsCollection->insertOne(
['_id' => $idCounter, 'product_name' => $productName, 'product_quantity' => $productQuantity]
);
Related
I'm coming from Java programming and I'm trying to apply my knowledge in OOP style programming in PHP.
So, I tried to create a utility class to connect to database just like how I usually do it in Java where I create a static method to get the database connection.
However, after spending hours I still can't fix the error.
DBHelper.php
<?php
class DBHelper
{
protected $db_name = 'myDb';
protected $db_user = 'root';
protected $db_pass = '';
protected $db_host = 'localhost';
public function obtainConnection()
{
$mysqli_instance = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
return $mysqli_instance;
}
}
?>
There are no errors in this file
Then I tried to use it on another file called login.php
login.php
<?php
if (isset($_POST['submit'])) {
include "/DBUtility/DBHelper.php";
$username = $_POST['username']; //s means string
$password = $_POST['password']; // s means string
echo "<br/> Username value: " . $username;
echo "<br />Password value: " . $password;
}
if (empty($username) || empty($password) ) {
echo "Fill out the fields!";
} else {
//PREPARE THE PreparedStatment or Stored Procedure
$dbHelper = new DBHelper();
$connection = $dbHelper->obtainConnection();
$preparedStatement = $connection->prepare('CALL getUserRoleByLogin(?, ?)'); //getUserRoleByLogin() is the name of stored proc in mysql db
$preparedStatement->bind_param('ss', $username, $password); //assign arguments to ? ?
$preparedStatement->execute();//execute the stored procedure. This will return a result
$userRole = $preparedStatement->store_result();
$countOfRows = $preparedStatement->num_rows;
?>
I read every related question about the Fatal error: Cannot redeclare class CLASSNAME error. I tried following the instructions given by many which is to use require_once("DBHelper.php"); instead of include("DBHelper.php");
but still can't get rid of the error.
I tried making the obtainConnection() static and called it via DBHelper::obtainConnection(); but with no luck. Same error message.
I get the error on opening brace of class DBHelper {
I hope you can help me with this.
Thank you.
A couple tips you should do when doing OOP in PHP:
1) I would maybe rethink about not baking the db credentials into your class directly, it makes it harder/more cumbersome to modify them via UI if you wanted to implement a UI control mechanism down the line. Instead, try making a define or maybe a json pref file or a dynamically-created php file that contains an array, something like that. I will do a define because it's the easiest to demonstrate:
/config.php
# You can create a series of defines including the database
define('DB_HOST','localhost');
define('DB_NAME','dbname');
define('DB_USER','root');
define('DB_PASS','dbpassword');
# To maximize compatibility it's helpful to define fwd/back slash
define('DS',DIRECTORY_SEPARATOR);
# It is helpful to create path defines for easy file inclusion
define('ROOT_DIR',__DIR__);
define('CLASSES',ROOT_DIR.DS.'classes');
# Start session
session_start();
2) Create a class autoloader in the config.php file which then allows you to not have to manually include/require classes in pages. It will automatically include them:
spl_autoload_register(function($class) {
if(class_exists($class))
return;
# This will turn a namespace/class into a path so should turn:
# $db = new \DBUtility\DBHelper();
# into:
# /var/www/domain/httpdocs/classes/DBUtility/DBHelper.php
$path = str_replace(DS.DS,DS,CLASSES.DS.str_replace('\\',DS,$class).'.php');
# If the class file is located in the class folder, it will include it
if(is_file($path))
include_once($path);
});
3) I am going to create a static connection so you don't create a new connection every time (also I will use PDO):
/classes/DBUtility/DBHelper.php
<?php
namespace DBUtility;
class DBHelper
{
protected $query;
private static $con;
public function connection()
{
# This will send back the connection without making a new one
if(self::$con instanceof \PDO)
return self::$con;
# I like to catch any pdo exceptions on connection, just incase.
try {
# Assign the connection
self::$con = new \PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USER,DB_PASS);
}
catch(\PDOException $e) {
# Here you can just die with a more user-friendly error.
# It would be helpful to save the actual error to a log file
$msg = $e->getMessage();
# I would put your log outside the root or in a protected folder
$txt = realpath(ROOT_DIR.DS.'..').DS.'errors'.DS.'sql.txt';
# Make a directory if none set
if(!is_dir(pathinfo($txt,PATHINFO_DIRNAME))) {
# Make the directory
if(mkdir(pathinfo($txt,PATHINFO_DIRNAME),0744,true)) {
# Save to log file
file_put_contents($txt,$msg.PHP_EOL);
}
}
else {
# Save to log file
file_put_contents($txt,$msg.PHP_EOL);
}
die("Site is under maintenance.");
}
}
# It would be helpful to create a query that will bind and not bind
public function query($sql,$bind = false)
{
if(is_array($bind)) {
foreach($bind as $key => $value) {
$sKey = ":{$key}";
$bindArr[$sKey] = $value;
}
$this->query = $this->connection()->prepare($sql);
$this->query->execute($bindArr);
}
else {
# The second "query" on this is the method from PDO, not the
# "query" method from this class
$this->query = $this->connection()->query($sql);
}
return $this;
}
public function getResults()
{
if(empty($this->query))
return false;
while($result = $this->query->fetch(\PDO::FETCH_ASSOC)) {
$row[] = $result;
}
return (isset($row))? $row : false;
}
}
# If your page ends with a php tag, you should just remove it. It will
# protect against empty spaces that may cause "header already sent" errors
3a) I use something similar to this to autoload functions:
/classes/Helper.php
class Helper
{
public static function autoload($function)
{
if(function_exists($function))
return;
$path = ROOT_DIR.DS.'functions'.DS.$function.'.php';
if(is_file($path))
include_once($path);
}
}
4) Create useful/reusable functions or class/methods
/functions/getUserRole.php
function getUserRole($username,$password,\DBUtility\DBHelper $DBHelper)
{
return $DBHelper->query('CALL getUserRoleByLogin(:0, :1)',array($username,$password))->getResults();
}
/index.php
# Include the config file
require_once(__DIR__.DIRECTORY_SEPARATOR.'config.php');
if (isset($_POST['submit'])) {
# No need for this line ->> include "/DBUtility/DBHelper.php";
# Use trim to remove empty spaces on the left and right
$username = trim($_POST['username']);
$password = trim($_POST['password']);
}
if (empty($username) || empty($password) ) {
echo "Fill out the fields!";
} else {
# User our function autoloader to include this function
Helper::autoload('getUserRole');
# Use the function and inject the DB class
$userRoles = getUserRole($username,$password,new \DBUtility\DBHelper());
$count = count($userRoles);
echo "Count: {$count}";
echo '<pre>';
print_r($userRoles);
echo '</pre>';
}
Hi I am new to cassandra database. I am downloaded phpcassa from
https://github.com/mauritsl/php-cassandra.
When I tried to autoload cassandra library from application/config/autoload.php I got non existence class cassandra error.
Please help me to solve this issue.
o Place all Cassandra related files into application/library/ folder.
Remove the name space from each Cassandra class file.
"namespace Cassandra;"
Your file name and class name should match to load the library in auto load function in codeigniter.
Cassandra file class name is "Connection".
Change the class name as "Cassandra"
Your constructor expects a parameter to connect the database. You can't pass parameters while loading autoload library.
Change your constructor method name as connect
Using $this->cassandra->connect($host,$keyspace,$options) you can process the connection.
Rename the __construct into connect
/**
* Connect to Cassandra cluster.
*
* #param mixed $host
* Hostname as string or array of hostnames.
* #param string $keyspace
* #param array $options
*/
public function connect($host, $keyspace = NULL, $options = array()) {
$this->options += $options;
if (empty($host)) {
throw new InvalidArgumentException('Invalid host');
}
if (!is_array($host)) {
$host = array($host);
}
shuffle($host);
while ($host) {
$hostname = array_pop($host);
try {
$this->transport = new Transport($hostname, $this->options['connect_timeout'], $this->options['stream_timeout']);
break;
}
catch (Exception $e) {
if (empty($host)) {
// No other hosts available, rethrow exception.
throw $e;
}
}
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I am trying to use PDO to connect to a SQL Server database. I have been struggling with it for a little bit now I get this Fatal error on my page where I am trying to connect to SQL Server
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[IMSSP]: This extension requires the Microsoft SQL Server 2012 Native Client ODBC Driver to communicate with SQL Server. Access the following URL to download the Microsoft SQL Server 2012 Native Client ODBC driver for x86: http://go.microsoft.com/fwlink/?LinkId=163712'
I have downloaded the drives from
http://www.microsoft.com/en-us/download/details.aspx?id=20098 (SQLSRV30.EXE)
I have placed those drivers in the ext directory where php is installed on the Server 2008 R2 server.
I also have added these 2 lines at the end of the extension list in the php.ini file
extension=php_pdo_sqlsrv_53_nts.dll
extension=php_sqlsrv_53_nts.dll
I am using PH PVersion 5.3.19
Server API CGI/FastCGI
Thread Safety disabled
I do see pdo_sqlsrv but I don't see a Client API Version.
What else do I need to do to be able to use PDO to connect to the remote server that has SQL databses? Do I need to install anything on the remote servers?
this is a screenshot of my php my admin section
This is my connection class
<?php
class connection {
private $connString;
private $userName;
private $passCode;
private $server;
private $pdo;
private $errorMessage;
protected $lastQueryTime;
protected $lastQuery;
private $pdo_opt = array (
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
);
function __construct($dbName = DATABASE_NAME, $serverName = DATABASE_HOST){
//sets credentials
$this->setConnectionCredentials($dbName, $serverName);
//start the connect
$this->startConnection();
}
function startConnection(){
$this->pdo = new PDO($this->connString, $this->userName, $this->passCode, $this->pdo_opt);
if( ! $this->pdo){
$this->errorMessage = 'Failed to connect to database. Please try to refresh this page in 1 minute. ';
$this->errorMessage .= 'However, if you continue to see this message please contact your system administrator.';
echo $this->getError();
}
}
//this will close the PDO connection
public function endConnection(){
$this->pdo = null;
}
//return a dataset with the results
public function getDataSet($query, $data = NULL)
{
$start = microtime(true);
$cmd = $this->pdo->prepare( $query );
$cmd->execute($data);
$ret = $cmd->fetchAll();
//$cmd->closeCursor();
$this->lastQueryTime = microtime(true) - $start;
$this->lastQuery = $query;
return $ret;
}
public function processQuery($query, $data = NULL)
{
$start = microtime(true);
//$this->pdo->beginTransaction();
$cmd = $this->pdo->prepare( $query );
$ret = $cmd->execute($data);
//$this->pdo->commit();
//$cmd->closeCursor();
$this->lastQueryTime = microtime(true) - $start;
$this->lastQuery = $query;
return $ret;
}
//return last insert id
public function lastInsertId($name = NULL) {
if(!$this->pdo) {
return false;
}
return $this->pdo->lastInsertId($name);
}
public function getOneResult($query, $data = NULL){
$cmd = $this->pdo->prepare( $query );
$cmd->execute($data);
return $cmd->fetchColumn();
}
public function getError(){
if($this->errorMessage != '')
return $this->errorMessage;
else
return true; //no errors found
}
//this where you need to set new server credentials with a new case statment
function setConnectionCredentials($dbName, $serv){
switch($serv){
//MS SQL server
case 'SQLSERVER':
$this->connString = 'sqlsrv:server='.$serv.';database='.$dbName;
$this->userName = 'username';
$this->passCode = 'password';
break;
//the defaults are predefined in the APP_configuration file - DO NOT CHANGE THE DEFAULT
default:
$this->connString = 'mysql:host='.DATABASE_HOST.';dbname='.DATABASE_NAME.';charset=utf8';
$this->userName = DATABASE_USERNAME;
$this->passCode = DATABASE_PASSWORD;
break;
}
}
public function lastQueryTime() {
if(!$this->lastQueryTime) {
throw new Exception('no query has been executed yet');
}
return $this->lastQueryTime;
}
public function lastQuery() {
if(!$this->lastQuery) {
throw new Exception('no query has been executed yet');
}
return $this->lastQuery;
}
}
?>
This is how I use my class to pull a dataset
<?php
include('connection.php');
$sql_db = new connection('databaseName','SQLSERVER');
$call_details = $sql_db->getDataSet('SELECT
LocalUserId AS loginName,
RemoteNumberCallId AS PhoneNumber,
SUM(CallDurationSeconds + HoldDurationSeconds + LineDurationSeconds) AS totalTalk
FROM dbo.CallDetail WHERE LocalUserId = \'blah\' AND RemoteNumberCallId = \'123456789\'
GROUP BY LocalUserId, RemoteNumberCallId');
$call_details->endConnection();
?>
I have even tried this code so I won't use my class and I still get the same error
$ss = new PDO("sqlsrv:server=SQLSERVER; Database=databaseName", "userName", "Password");
I have replaced the
extension=php_sqlsrv_53_nts.dll
extension=php_pdo_sqlsrv_53_nts.dll
With
extension=php_pdo_sqlsrv_53_nts_vc9.dll
extension=php_sqlsrv_53_nts_vc9.dll
Insted on using SQLSRV30.EXE I used the SQLSRV20.EXE This worked.
#FreshPrinceOfSo Thanks for your help :)
Thanks :)
My personal installation for Windows Server 2008 R2 and configuration with PHP/SQL Server.
Download the latest stable .zip release of VC9 x86 Non Thread Safe from PHP Downloads
Extract into your PHP directory
Download Microsoft Drivers 3.0 for PHP for SQL Server
Extract into your PHP directory\ext
Write the following extensions to php.ini
[PHP_SQLSRV_54_NTS]
extension=php_sqlsrv_54_nts.dll
[PHP_PDO_SQLSRV_54_NTS]
extension=php_pdo_sqlsrv_54_nts.dll
I have create a class called Database.php for interacting with MySql database using Pear Db class.
Database.php
<?php
require_once('DB.php');
require_once('cException.php');
class DataBase
{
private $dsn = 'mysql://root:xxxxxx#localhost/avatar';
private $conn;
//Constructor
function __construct()
{
global $conn;
$this->conn = DB::connect($dsn);
if(DB::isError($conn))
{
throw new DatabaseConnectionException();
}
}
//destructor
function __destruct()
{
$this->conn->disconnect();
}
public function select($query)
{
$conn->setFetchMode(DB_FETCHMODE_ASSOC);
$result = & $conn->query($query);
if(DB::isError($result))
{
return new SelectCommandException($result->getMessage());
}
return $result;
}
static public function instance()
{
static $objDB;
if(! isset($objDB))
{
$objDB = new DataBase();
}
return $objDB;
}
?>
And I am calling this class from a sample file test.php
test.php
<?php
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
error_reporting(E_ALL);
require_once 'Database.php';
try
{
$db = DataBase::instance();
}
catch (DatabaseConnectionException $ex1)
{
echo $ex1->toString();
}
try
{
$sql = "Select * from register";
$result = $db->select($sql);
var_dump($result);
}
catch (SelectCommandException $ex2)
{
echo $ex2->toString();
}
?>
When I run test.php I get the following error
Warning:
require_once(/usr/share/pear/DB.php):
failed to open stream: No such file or
directory in
/var/www/Avatar/Database.php on line 2
Fatal error: require_once(): Failed
opening required
'/usr/share/pear/DB.php'
(include_path='.:/usr/share/php:/usr/share/pear')
in /var/www/Avatar/Database.php on
line 2
I don't know why I am getting this error. In phpinfo() it shows include_path .:/usr/share/php:/usr/share/pear .:/usr/share/php:/usr/share/pear
I am using php5 and I even tried installing php-pear package, still I get the same error.
I don't understand what's wrong here. Can someone please point me in a right direction.
Note : I have not installed php5 using sudo apt-get install php5. I have downloaded php5 packages using Keryx application.
Looks you did not install DB package, try in command prompt, do
pear list
If no package of DB is installed, you can installed it with
pear install DB
example from documentation
im trying to extend the mysqli class in php in order to create a wrapper class. I would like this class to manage multiple connections.. I am currently at a very early stage and have hit a problem:
Auth Connected no: 1
1045:Access denied for user 'rootty'#'localhost' (using password: YES)
Segmentation fault
It seems when the second connection has an error a segmentation fault is created however connection one errors correctly..
<?php
class mysqli_ls extends mysqli
{
private $link = array();
private $link_no = 0;
/* ************************************************************ */
public function __construct()
{
}
/* ************************************************************ */
public function open($host='', $user='', $pass='', $port='3306', $database='')
{
if ( empty($host) || empty($user) || empty($pass) || empty($database) )
{
$this->error[] = "Missing required connection variables";
return false;
}
$this->link_no++;
#$this->link[ $linkno ] = $this->connect($host, $user, $pass, $database, $port);
if ($this->connect_errno)
{
$this->error[] = $this->connect_errno .':'. $this->connect_error;
return false;
}
return $this->link_no;
}
######Test script
#!/usr/bin/php
<?php
require_once('mysqli.class.php');
$_mysqli = new mysqli_ls;
$_auth = $_mysqli->open('localhost','root','xx','3306','auth');
if ($_auth === false) print $_mysqli->get_last_error() ."\n";
else print 'Auth Connected no: '. $_auth ."\n";
$_trak = $_mysqli->open('localhost','root','sxx','3306','wlr_tracker');
if ($_trak === false) print $_mysqli->get_last_error() ."\n";
else print 'Trak Connected no: '. $_trak ."\n";
I would report this to the PHP/mysqli devs. A scripting language segfaulting is most likely an internal bug you cannot fix - while it might be possible to create a workaround the proper way is to get it fixed in the C code.