Class PDO not found when calling a singleton class - php

can anyone tell me what could cause this error "Fatal error: Class PDO not found"
when I call the singleton class like this: $db = db::krijgInstantie();
I use an mvc design and this error is weird, because I use the same code for another site
public static function krijgInstantie()
{
if (!self::$instantie)
{
$config = config::krijgInstantie();
$db_type = $config->config_waarden['database']['db_type'];
$hostnaam = $config->config_waarden['database']['db_hostnaam'];
$dbnaam = $config->config_waarden['database']['db_naam'];
$db_wachtwoord = $config->config_waarden['database']['db_wachtwoord'];
$db_gebruikersnaam = $config->config_waarden['database']['db_gebruikersnaam'];
$db_poort = $config->config_waarden['database']['db_poort'];
self::$instantie = new PDO("$db_type:host=$hostnaam;port=$db_poort;dbname=$dbnaam",$db_gebruikersnaam, $db_wachtwoord);
self::$instantie-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return self::$instantie;
}
thanks, Richard

Your PHP installation is missing the PDO module. Check your PHP.ini.
See also: http://php.net/manual/en/pdo.installation.php

Related

PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function Kit\core::__construct() on PDO class

I am currently looking at improving my PHP knowledge and creating websites to a better extent by using classes and such but I've ran into an issue when trying to allow other classes in separate files to access the PDO connection that I've sent up. I've tried hundreds of resolutions which have been inputted onto this site but can't seem to figure it out at all and can't seem to understand where I'm going wrong.
I'm being met with the following error:
[16-Sep-2022 11:05:02 UTC] PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function Kit\core::__construct(), 0 passed in /home/liamapri/public_html/kit/global.php on line 24 and exactly 1 expected in /home/liamapri/public_html/kit/app/class.core.php:11
Stack trace:
#0 /home/liamapri/public_html/kit/global.php(24): Kit\core->__construct()
#1 /home/liamapri/public_html/index.php(3): include_once('/home/liamapri/...')
#2 {main}
thrown in /home/liamapri/public_html/kit/app/class.core.php on line 11
I have a global.php file which will be added to each individually page such as /home /index etc, it references all the files that I'll need and starts the session from it, see below:
error_reporting(E_ALL ^ E_NOTICE);
define('C', $_SERVER["DOCUMENT_ROOT"].'/kit/conf/');
define('A', $_SERVER["DOCUMENT_ROOT"].'/kit/app/');
define('I', 'interfaces/');
// Management
require_once C . 'config.php';
// Interfaces
require_once A . I . 'interface.engine.php';
require_once A . I . 'interface.core.php';
require_once A . I . 'interface.template.php';
// Classes
require_once A . 'class.engine.php';
require_once A . 'class.core.php';
require_once A . 'class.template.php';
// OBJ
$engine = new Kit\engine();
$core = new Kit\core();
$template = new Kit\template();
// Start
session_start();
$template->Initiate();
This references the class.engine.php first which is where I have created the database connection class, as shown below:
namespace Kit;
use PDO;
if(!defined('IN_INDEX')) { die('Sorry, this file cannot be viewed.'); }
class engine
{
public $pdo;
public function __construct()
{
global $_CONFIG;
$dsn = "mysql:host=".$_CONFIG['mysql']['hostname'].";dbname=".$_CONFIG['mysql']['database'].";charset=".$_CONFIG['mysql']['charset'].";port=".$_CONFIG['mysql']['port'].";";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$this->pdo = new PDO($dsn, $_CONFIG['mysql']['username'], $_CONFIG['mysql']['password'], $options);
} catch (\PDOException $e) {
print "<b>An error has occurred whilst connecting to the database:</b><br />" . $e->getMessage() . "";
die();
}
}
}
$connection = new engine();
I'm then trying to run a PDO query on another class (class.core.php) and keep getting met with either a PDO can't be found error or the one described above.
See the file below:
namespace Kit;
if(!defined('IN_INDEX')) { die('Sorry, this file cannot be viewed.'); }
class core implements iCore
{
public $connection;
public function __construct($connection)
{
$this->connection = $connection;
}
public function website_settings()
{
$qry = $this->connection->pdo->prepare("SELECT `website_name` FROM `kit_system_settings`");
$qry->execute([]);
if ($qry->rowCount() == 1) { while($row = $qry->fetch()) { return $row; } }
}
}
Sorry if this is a simple fix but I really can't see where I'm going wrong.
Look in your global .php on Line 24 (its probably this line: $core = new Kit\core();)
In your class.core.php you tell the constructor that it will get a connection, but in your global.php you dont give constructor (when you initialize a class) any argument.
That's what this error is telling you
PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function Kit\core::__construct(), 0 passed
Just guessing, but i think
$core = new Kit\core($engine->pdo);
will fix your issue.

How to make php class available in function

I am using a third party class that works well as long as I use it in the main body of my PHP script. If I try to use it in a function that is called from main, it gets a "PHP Fatal error: Class 'RouterOS\Util' not found error". What do I need to do in the function so it can use the class?
<?php
require_once '/usr/local/sbrc/MTAPI/vendor/autoload.php';
...
GetNextRouter($loginData[0]['User'], $loginData[0]['Password'], $firstAddress[0]['IPAddress']);
...
}
function GetNextRouter($UserID, $Pass, $Address) {
$util = new RouterOS\Util($client = new RouterOS\Client($Address, $UserID, $Pass));
...
}
The error occurs on the $util = new RouterOS\Util line.
Adding
use PEAR2\Net\RouterOS;
solved my issue

Strange reflection behavior in php Laravel 4

This seems like a fairly simple reflection problem, yet I can't figure it our. I use Laravel 4.2 on Debian with PHP 5.6.6-1.
Basicly what happens is that I want to spawn a new object from a class in a Laravel QueueHandler like so:
$className = 'MyClass';
$myobject = new $className ();
and this doesn't work. I tried everything I can possibly think of and have no clue where to look. This code doesn;t work while it should:
<?php
use Pronamic\Twinfield\Secure\Config;
use Pronamic\Twinfield\Customer\CustomerFactory;
class TwinfieldQueueHandler {
private $twinfieldConfig = null;
...
try {
$twinfieldFactoryClass = 'CustomerFactory';
//returns 0
echo strcmp('CustomerFactory', $twinfieldFactoryClass);
//works
$test0 = new CustomerFactory ($this->twinfieldConfig);
//throws an exeption with message: "Class CustomerFactory does not exist"
$r = new ReflectionClass($twinfieldFactoryClass);
$test1 = $r->newInstanceArgs($this->twinfieldConfig);
//gives error PHP Fatal error: Class 'CustomerFactory' not found in {file} on line {line}
$test2 = new $twinfieldFactoryClass ($this->twinfieldConfig);
} catch (Exception $e) {
Log::error($e->getMessage());
}
Has anyone got any pointers on where to look and how to debug this?
ReflectionClass will ignore your current namespace and use statements completely. You have to specify the fully qualified name of the class:
$r = new ReflectionClass('Pronamic\Twinfield\Customer\CustomerFactory');
As a user points out on php.net:
To reflect on a namespaced class in PHP 5.3, you must always specify the fully qualified name of the class - even if you've aliased the containing namespace using a "use" statement.
Note that you could work around this by passing an object:
$test0 = new CustomerFactory ($this->twinfieldConfig);
$r = new ReflectionClass($test0);

Closing my mySQL connection

I'm a .Net developer that have taken over a PHP project. This project has a database layer that looks like this:
<?php
class DatabaseManager {
private static $connection;
const host = "projectname.mysql.hostname.se";
const database = "databaseName";
const username = "userName";
const password = "password";
public function __construct()
{
}
public function instance($_host = null, $_username = null, $_password = null)
{
if(!self::$connection)
{
if(!$_host || !$_username || !$_password)
{
$host = self::host;
$username = self::username;
$password = self::password;
}else{
$host = $_host;
$username = $_username;
$password = $_password;
}
self::$connection = mysql_connect($host, $username, $password);
$this->setDatabase();
}
return self::$connection;
}
public function setDatabase($_database = null)
{
if(!$_database)
{
$database = self::database;
}else{
$database = $_database;
}
$connection = $this->instance();
mysql_select_db($database, $connection) or die(mysql_error());
}
} ?>
I have written a php file that uses this layer but after a while i got these mysql errors implying i didn't close my connections which i hadn't. I try to close them but know i get other weird errors like system error: 111. Very simplyfied my php file looks like this:
<?php
$return = new stdClass();
$uid = '9999999999999';
$return->{"myUid"} = $uid;
$dm = new DatabaseManager();
$dmInstance = $dm->instance();
/* MY CLICKS */
$sql = sprintf("SELECT count(*) as myClicks FROM clicks2011, users2011 WHERE clicks2011.uid = users2011.uid AND users2011.uid = %s AND DATEDIFF(DATE(at), '%s') = 0 AND exclude = 0", mysql_real_escape_string($uid), mysql_real_escape_string($selectedDay));
$result = mysql_query($sql, $dmInstance) or die (mysql_error());
$dbResult = mysql_fetch_row($result);
$return->{"myClicks"} = $dbResult[0];
mysql_close($dmInstance);
echo json_encode($return); ?>
Okay, I'm going to post this as an answer because I think one (possibly both) of these things will help you.
First: You don't need to manually close your MySQL connections. Unless you have set them up so that they persist, they will close automatically. I would avoid doing that unless you determine that every other problem is NOT the solution.
In addition, I would switch to using prepared statements. It's more secure, and pretty future-proof. I prefer PHP's PDO over mysqli, but that's up to you.
If you'd like to look over an example of a simple PDO object to take the many lines out of creating prepared statements and connections and getting results, you can look at my homebrew solution.
Second: "System Error 111" is a MySQL error. From what I've read, it appears that this error typically occurs when you are using PHP and MySQL on the same server, but telling PHP to connect to MySQL via an IP address. Switch your $host variable to 'localhost'. It is likely that this will solve that error.
The problem here is you're calling mysql_close and not specifying a valid mysql connection resource object. You're, instead, trying to close an instance of the DatabaseManager object.
You'll probably want to run mysql_close(DatabaseManager::connection); which is where the DatabaseManager is storing the resource object.
Additionally, I'd personally recommend you learn PDO or use the mysqli drivers. In future releases of PHP the built in mysql functions will be moved into E_DEPRECATED
Try implement __destrcut
public function __destruct()
{
mysql_close(self::$connection)
}
Then simply use unset($dm);

php and webservices

I have a wsdl file and i am trying to call it from a php class. I am using the following code:
<?php
include ("dbconn.php");
class dataclass
{
function getCountries()
{
$connection = new dbconn();
$sql = "SELECT * FROM tblcountries";
$dataset = $connection -> connectSql($sql);
return $dataset;
}
function getTest()
{
$connection = new dbconn();
$sql = mysql_query('CALL sp_getTest');
$dataset = $connection -> connectSql($sql);
return $dataset;
}
##-------------------------------------------CUSTOMER METHODS-------------------------------------------
function registerCustomer($username,$name,$surname,$password,$email,$country,$tel)
{
$connection = new dbconn();
$sql="INSERT INTO tblcustomer (customer_username, customer_password, customer_name, customer_surname,
customer_email, customer_country, customer_tel)
VALUES('$username','$name','$surname','$password','$email','$country','$tel')";
$dataset = $connection -> connectSql($sql);
}
ini_set("soap.wsdl_cache_enabled", "0");
// start the SOAP server - point to the wsdl file
$webservice = new SoapServer("http://localhost/dataobjects/myWebservice.wsdl", array('soap_version' => SOAP_1_2));
// publish methods
$webservice->addFunction("getCountries");
$webservice->addFunction("registerCustomer");
// publish
$webservice->handle();
}
?>
It is all the time giving me a problem with ini_set("soap.wsdl_cache_enabled", "0");
The error is:
Parse error: syntax error, unexpected T_STRING, expecting T_FUNCTION in C:\Program Files\xampplite\htdocs\dataobjects\dataClass.php on line 47
I believe it is because you have ini_set() call in the body of your class. Put it at the top of the file or in the constructor if you have one.
class dataClass
{
function registerCustomer()
{
// some stuff
}
ini_set(/*args*/); // it's illegal to put instructions in the body of the class
}
Now I see the whole thing. You probably want to close the class with a closing backet before line 47.
You let the parser think "0" is a string, and not a number, please remove the quotes!
Edit 1 If that wouldn't work, your error must be before that line, please post the full code for review.
Edit 2 The code you provided was running inside the class, you miss a bracket before the line with ini_set.
Move the last } in front of ini_set(...)
By the way, you said you want to call a web service, but you are creating a server which may be called by others.
To call a web service, try something like this:
try{
$client = new SoapClient($service, array('location' =>"http://example.org/myWebService"));
$parameter1 = new myWebServiceParameter();
$result = $client->myWebServiceFunction($parameter1);
} catch (Exception $e) {
// handle errors
}
myWebServiceParameter must be any class with a member variable foreach WSDL message attribute of the same name.
And myWebServiceFunction is the name of the web service method.

Categories