Pear DB class not found - php

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

Related

PHP - Create PDO Connection using namespace

I have a project folder name utilities.
The list of directory is:
- utilities
- tli
- database
Connection.php
index.php
The Connection.php is PDOConnection.
The code is:
<?php
namespace app\tli\database;
use PDO;
use PDOException;
Class Connection
{
private $server = "mysql:host=localhost;dbname=ytsurumaru_hanwa_coil_v.2";
private $user = "root";
private $pass = "";
private $options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,);
protected $con;
public function openConnection()
{
try {
$this->con = new PDO($this->server, $this->user, $this->pass, $this->options);
return $this->con;
} catch (PDOException $e) {
return "There is some problem in connection: " . $e->getMessage();
}
}
public function closeConnection()
{
$this->con = null;
}
}
UPDATED SOURCE
Now, I need this Connection instance in index.php
<?php
namespace app;
use app\tli\database\Connection;
use PDOException as PDOEx;
require('tli/database/Connection.php');
try {
$connection = new Connection(); // not found
$connection->openConnection();
} catch (PDOEx $e) {
echo $e->getMessage();
}
When I run it,
D:\wamp64\www\utilities\tli>php index.php
Warning: require(tli/database/Connection.php): failed to open stream: No such file or directory in D:\wamp64\www\utilities\tli\index.php on line 8
Fatal error: require(): Failed opening required 'tli/database/Connection.php' (include_path='.;C:\php\pear') in D:\wamp64\www\utilities\tli\index.php on line 8
How to solved this, is my namepace have a problem ?
Isn't this enough to access your database connection?
require 'tli/database/Connection.php';
Then, since you are in a different name space and you are not aliasing, in your 'try catch block' you should instead of:
$connection = new Connection(); // not found
Do something like:
$connection = new \tli\database\Connection();
Make sure to set your paths right.
OR
You can alias to a different name like so:
namespace app;
require 'tli/database/Connection.php';
use tli\database\Connection as MyConnection;
$connection = new MyConnection();
You need to use one of these:
include('tli/database/Connection.php')
include_once('tli/database/Connection.php')
require('tli/database/Connection.php')
require_once('tli/database/Connection.php')
or if you want some more automation use autoloader.
You may want to look at this SO question and all the linked things.

error in getting the fetching path

I actually trying to check my connection in connection file tester to check if it is connected to the database but the problem is I got this error
Warning: include(obj\database_connection\SqlHandler.php): failed to open stream: No such file or directory in /home/devhostt/public_html/bcc/gradingsystemmodule/root/root.php on line 16
Warning: include(): Failed opening 'obj\database_connection\SqlHandler.php' for inclusion (include_path='/home/devhostt/public_html/bcc/gradingsystemmodule:.:/opt/alt/php55/usr/share/pear:/opt/alt/php55/usr/share/php') in /home/devhostt/public_html/bcc/gradingsystemmodule/root/root.php on line 16
Fatal error: Class 'obj\database_connection\SqlHandler' not found in /home/devhostt/public_html/bcc/gradingsystemmodule/function/checkconnection.php on line 8
and here is my code to set & get the path (root.php)
<?php
error_reporting( E_ALL );
define("setRealpath", realpath("../"));
const ERROR_EXCEPTION_MESSAGE = "SOMETHING WENT WRONG HERE: ";
try
{
$getPath = array(setRealpath, get_include_path());
if(!set_include_path(implode($getPath, PATH_SEPARATOR)))
{
define("setRealpath", realpath("./"));
$getPath = array(setRealpath, get_include_path());
set_include_path(implode($getPath, PATH_SEPARATOR));
}
function GetClassFile($class)
{
$file = str_replace('/', '\\', $class).".php";
include $file;
}
spl_autoload_register('GetClassFile');
}
catch(Exception $x)
{
die(ERROR_EXCEPTION_MESSAGE.$x->getMessage());
}
?>
here is the file where my connection (SqlHandler.php).
<?php
namespace obj\connection_database;
use \PDO;
class SqlHandler extends Connection
{
const ERROR_EXCEPTION_MESSAGE = "SOMETHING WENT WRONG HERE:";
protected $db = null;
public function __construct()
{
$this->db = $this->getConnection();
}
public function checkConnection()
{
if($this->db)
{
return "CONNECTED";
}
return "NO CONNECTION";
}
}
?>
and lastly here in this file where i'm trying to check the connection(checkconnection.php)
<?php
error_reporting(E_ALL);
include "./root/root.php";
use \obj\database_connection\SqlHandler;
$checkConnection = new SqlHandler;
echo $checkConnection->checkConnection();
?>
now i found my mistake, the only mistake is that i'm using the old version of php, instead of using php 7.1 version , i'm using php 5. so i change it and it works.

MongoDb error with php 7 on xampp CodeIgniter

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]
);

PHP: Using an SSH class inside a different class constructor

I am still rather green when it comes to PHP. Not quite sure where the issue comes in here. I am using a rather simple SSH2 class (https://www.phpclasses.org/browse/file/34450.html) that works well for my needs, or has until this point.
This is the class I have set up. I put the ssh connection into the constructor, and attempt to use $this->ssh throughout the rest of the class functions.
include ("/var/www/html/class/ssh2_class.php"); ##https://www.phpclasses.org/browse/file/34450.html
class crontab {
function __construct($host,$params) {
$this->host = $host;
$this->pubkey = $params['pubkey'];
$this->privkey = $params['privkey'];
$this->usr = $params['user'];
$this->port = $params['port'];
$this->secret = $params['secret'];
$this->ssh = new SSH2($this->host)
or die ("Unable to connect to ". $this->host ."!");
$this->ssh->auth($this->usr, $this->pubkey, $this->privkey, $this->secret)
or die ("Unable to authenticate to ". $this->host ."!");
}
function show($sudo) {
if ($sudo) { $sudo = "sudo"; } else { $sudo = ""; }
$cmd = $sudo."$sudo crontab -l";
$this->ssh->exec($cmd);
return ($this->ssh->output);
}
The issue I run into is in the return line of the show function above. The $this->ssh->exec($cmd); works without issue; I've tested it by simply touching a file.
PHP Notice: Undefined property: SSH2::$output in /home/mackay_c/scripts/deploy/deploy.class.php on line 26
I've searched around the web, and am at a bit of a loss as to why this occurs. The 'output' function in the SSH2 class is:
function output() {
return stream_get_contents($this->stream);
Any help would be appreciated.
return ($this->ssh->output())

Fatal error: can't find PHPUnit_Extensions_Database_PDB_DefaultDatabaseConnection in testcase.php

So I am trying to do some database testing in phpunit, and when trying to connect to the database, i get this error:
Fatal error: Class 'PHPUnit_Extensions_Database_DB_DefaultDatabaseConnection' not found in D:\xampp\php\pear\PHPUnit\Extensions\Database\TestCase.php on line 145
I opened up testcase.php and checked line 145. This is line 143-146:
protected function createDefaultDBConnection(PDO $connection, $schema = '')
{
return new PHPUnit_Extensions_Database_DB_DefaultDatabaseConnection($connection, $schema);
}
Also, heres the getConnection function i used, incase something is wrong with it:
public function getConnection() {
if ($this->conn === null) {
try {
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$this->conn = $this->createDefaultDBConnection($pdo, 'test');
} catch (PDOException $e) {
echo $e->getMessage();
}
}
return $this->conn;
}
You need to install the Database extension. Issue the following commands in the console:
sudo pear config-set auto_discover 1
sudo pear install --alldeps pear.phpunit.de/DbUnit
(On Windows you need to omit the sudo and probably locate the path to pear.exe)

Categories