php cant load internal PDO class - php

private function _connect(){
try {
$this->con = new PDO(''.$this->dbdriver.':host='.$this->dbhost.';dbname='.$this->dbname.'', $this->dbuser, $this->dbpass);
$this->con->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
$this->con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->con->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
return TRUE;
} catch (PDOException $e){
$reg = registry::_getInstance();
$reg->offsetSet('R_errors', $reg->offsetGet('R_errors').'</br>'.$e->getMessage());return false;
}
}
I am using the above code to connect to the database but am getting the following errors:
Fatal error: spl_autoload(): Class PDO could not be loaded in /home/tahidihomes/public_html/lib/core/pdo_mysql.core.php on line 72
What might be the problem?

Retry after PDO installation. If you get same error try again with the below code in top of index page
spl_autoload_extensions('.php, .class.php');
spl_autoload_register();

Related

PDO::setAttribute() doesn't seems to affect new PDO()?

I have this code
try {
$dbh = new PDO('mysql:host=localhost;dbname=db_informations', 'root', '');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage();
}
And it gives me the exception message:
SQLSTATE[HY000] [1049] Unknown database 'db_informations'
Because the correct name of my database is db_information only.
My question is, even if I don't include the line:
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
I still get the same exception and I think it's not necessary to use it? Is it?
This is simply because that's the behaviour of PDO::__construct() as you can read in the manual:
PDO::__construct() throws a PDOException if the attempt to connect to the requested database fails.
But if you don't set the error mode to Exception and you do:
try {
$dbh = new PDO('mysql:host=localhost;dbname=db_informations', 'root', '');
$dbh->query("SELECT * FROM aTableWhichDoesNotExists");
} catch(PDOException $e) {
echo $e->getMessage();
}
You won't get any excpetion message or error, because you didn't set the error mode. So you need to do this:
try {
$dbh = new PDO('mysql:host=localhost;dbname=db_informations', 'root', '');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->query("SELECT * FROM aTableWhichDoesNotExists");
} catch(PDOException $e) {
echo $e->getMessage();
}
To receive an exception, which you then can catch:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.atablewhichdoesnotexists' doesn't exist
Also if you just think logically:
setAttribute() needs to be used with ->, which means you need an instance of the class to call that method. So how would you be able to call that method, if the instance couldn't be created correctly?
(So that would mean setAttribute() would have to bee static, so that you can set something/call it before you take the instance of the class)

PHP Try Catch in Exception Handling

I have a database class dbconnect.php, and processform.php. Inside dbconnect.php there is a method for connecting to the database.
If there's an error, how do I throw an exception? Where do I put the try catch block, in the processform.php? People say I shouldn't echo an error directly from inside the class. Here's an example:
<?php
// dbconnect.php
class DbConnect
{
public function open_connection()
{
/* Should I do it like this? */
$this->conn = PDO($dsn, $this->username, $this->password);
if (!$this->conn) {
throw new Exception('Error connecting to the database.');
}
/* Or like this */
try {
$this->conn = PDO($dsn, $this->username, $this->password);
} catch (PDOException $e) {
echo 'Error: ', $e->getMessage(), '<br>';
}
}
?>
// processform.php
<?php
require_once 'dbconnect.php';
$pdo = new DbConnect($host, $username, $password);
try {
$pdo->open_connection();
} catch (PDOException $e) {
echo 'Error connecting to the database.');
}
?>
I really want to learn the correct way of implementing the try catch in my code.
You don't have to throw an exception manually, especially on a successful connect :-)
Instead you need to tell PDO that it needs to throw exceptions when something goes wrong and you can do that when you open your database connection:
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$this->conn = new PDO($dsn, $this->username, $this->password, $options);
Now you can put everything in try / catch blocks but that is not even necessary; if you don't do that, php will show you unhandled exceptions complete with a stack trace when you don't catch them manually.
And when you decide you want to fine-tune your error handling for your visitors, you can set your own exception handler using set_exception_handler(). That way you can handle everything at one place instead of wrapping different sections in try / catch blocks. Should you prefer that of course.
In my practice, I prefer to catch exception in bottom. I mean, second way in your DbConnect.
You can output error message to error log. And return an error code to front-end. So the front-end knows how to tell users an error occours in a friendly way.
What's more, you can use global error handler such as set_error_handler/set_exception_handler to do this. Redirect to an error page when error occours.

Problems connecting to MySQL using PDO

I've been trying to convert my application from using the depreciated mysql syntax to PDO for connecting to the database and performing queries, and it's been a pain so far.
Right now I have a class, db_functions.php, in which I'm trying to create a PDO connection to the database, as well as perform all the CRUD operations inside of.
Here is a sampling of the code:
db_functions.php
<?php
class DB_Functions {
private $db;
// constructor
function __construct() {
require_once 'config.php';
// connecting to mysql
try {
$this->$db = new PDO('mysql:host=localhost;dbname=gcm', DB_USER, DB_PASSWORD);
}
catch (PDOException $e) {
$output = 'Unable to connect to database server.' .
$e->getMessage();
exit();
}
}
// destructor
function __destruct() {
}
public function getAllUsers() {
try {
$sql = "select * FROM gcm_users";
//$result = mysql_query("select * FROM gcm_users");
$result = $this->$db->query($sql);
return $result;
}
catch (PDOException $e) {
$error = 'Error getting all users: ' . $e->getMessage();
}
}
With that code, i'm getting the following error:
Notice: Undefined variable: db in C:\xampp\htdocs\gcm\db_functions.php on line 12
Fatal error: Cannot access empty property in C:\xampp\htdocs\gcm\db_functions.php on line 12
Line 12 is:
$this->$db = new PDO('mysql:host=localhost;dbname=gcm', DB_USER, DB_PASSWORD);
How could I fix this so that I have a proper instance of a PDO connection to my database that I can use to create queries in other methods in db_functions, such as getAllUsers()
I used the answer found at How do I create a connection class with dependency injection and interfaces? to no avail.
TYPO
//$this->$db =
$this->db =
same here
//$this->$db->query($sql);
$this->db->query($sql);
and i also would use 127.0.0.1 instead of localhost to improve the performance otherwise making a connection will take very long... a couple of seconds just for connection...

Properties cannot be used outside of try catch blocks

I am trying to use properties inside try catch blocks.
The try catch blocks are inside classes.
I want to extend a specific class, making it the subclass of the class which handles exceptions.
The problem is, that when I try to use those variables from the subclass, it always says undefined. I have to delete both of classes in order to catch the properties. After reading some other answers here by adding a return statement (I added return 1) outside, inside of the try catch block, it doesn't seem to work and it always says undefined variable.
Any help?
The language is php
The source code without classes works perfect:
try
{
//$pdo variable to insert PDO object information
$pdo = new PDO('mysql:host=localhost;dbname=studenti', 'root', '');
//Set php to catch exceptions
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Set UTF-8 for character encodings
$pdo->exec('SET NAMES "utf8"');
}
//Catch error if unable to connect
catch(PDOException $e)
{
//error variable
$error = 'Unable to connect with database. ' . $e->getMessage();
//include file once and show on screen error message
include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/error.inc.php';
//Exit and don't process further
exit();
}
//Another Exception handling
try
{
//Select statement
$sql = 'SELECT * FROM dega';
$select = $pdo->query($sql);
}
catch(PDOException $e)
{
//error variable
$error = 'Unable to select table. ' . $e->getMessage();
//include file once and show on screen error message
include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/error.inc.php';
//Exit and don't process further
exit();
}
The source code with classes doesn't work:
<?php
//PDO class, connection with MySQL database
class Connect
{
function connection()
{
$pdo = null;
try
{
//$pdo variable to insert PDO object information
$pdo = new PDO('mysql:host=localhost;dbname=studenti', 'root', '');
//Set php to catch exceptions
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Set UTF-8 for character encodings
$pdo->exec('SET NAMES "utf8"');
}
//Catch error if unable to connect
catch(PDOException $e)
{
//error variable
$error = 'Unable to connect with database. ' . $e->getMessage();
//include file once and show on screen error message
include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/error.inc.php';
//Exit and don't process further
exit();
}
}
}
class Select extends Connect
{
function selection()
{
//Another Exception handling
try
{
//Select statement
$sql = 'SELECT * FROM dega';
$select = $pdo->query($sql);
}
catch(PDOException $e)
{
//error variable
$error = 'Unable to select table. ' . $e->getMessage();
//include file once and show on screen error message
include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/error.inc.php';
//Exit and don't process further
exit();
}
}
}
//Output if successful
$error = 'Database connection established.';
include $_SERVER['DOCUMENT_ROOT'] . '/inc/error.inc.php';
?>
You have no subclass. Object Inheritance
You have no properties. Properties
Read about Classes and Objects.
class Connect
{
protected $pdo = null;
public function connection()
{
$pdo = null;
try
{
$this->pdo = new PDO('mysql:host=localhost;dbname=studenti', 'root', '');
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->exec('SET NAMES "utf8"');
} catch (PDOException $e)
{
$error = 'Unable to connect with database. ' . $e->getMessage();
include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/error.inc.php';
exit();
}
}
}
class Select extends Connect
{
function selection()
{
try
{
$sql = 'SELECT * FROM dega';
$select = $this->pdo->query($sql);
} catch (PDOException $e)
{
$error = 'Unable to select table. ' . $e->getMessage();
include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/error.inc.php';
exit();
}
}
}
Put $pdo just before connection():
class Connect
{
protected $pdo = null; // or var $pdo = null;
function connection()
{
...
Inside the function it's a local variable not a class level property.
EDIT:
PHP requires $this-><class-variable> to access class properties inside functions. (Check out #Sectus's answer below.) Just using $pdo is creating a local variable on the fly (in both the methods) but gives an error in only selection() because that's where query() is being invoked without initializing a PDO() object first.

PHP PDO SQLite prepared statement issues

I am trying to migrate a PHP app from MySQL to SQLite, and some things that used to work, simply stopped working now. I am using PDO through a custom database wrapper class (the class is a singleton, seems logical to do it like that).
The problem:
When trying to execute a query on a prepared statement, it throws a "fatal error: Call to a member function execute() on a non-object ...".
Relevant code (narrowed it down to this, after some hours of var_dumps and try-catch):
Connection string:
$this->connection = new PDO("sqlite:"._ROOT."/Storage/_sqlite/satori.sdb");
Obviously, the $connection variable here is a private variable from the class.
The error happens here (inside a function that is supposed to perform database insert):
try{
$statement = self::getInstance()->connection->prepare($sql);
}catch (PDOException $e){
print $e->getMessage;
}
try{
var_dump($statement);
$statement->execute($input);
}catch (Exception $e){
print $e->getMessage();
}
More accurately, it happens when I try to $statement->execute($input).
Any help appreciated. Thanks.
You are probably getting a mySQL error when the statement is being prepared, but you don't have PDO configured to throw an exception in case of an error.
<?php
$dbh = new PDO( /* your connection string */ );
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
// . . .
?>
try declaring the $statement variable outside the first try block. e.g.
$statement = null;
try{
$statement = self::getInstance()->connection->prepare($sql);
}catch (PDOException $e){
print $e->getMessage;
}
try{
var_dump($statement);
$statement->execute($input);
}catch (Exception $e){
print $e->getMessage();
}

Categories