Trying to get PDO Connection to Establish - php

I have been working on getting a PDO connection to establish within a class for the better half of a day. My problem is that as soon as I try to hit the new PDO(...) I get nothing, no errors nothing. Whatever I have after that will never run but my console will still be operational waiting for input. I have tried connecting in a few places including the "Driver" file where again, it doesn't do anything after I run the new PDO(...) instantiation. Here is part of my Database Class:
namespace App\Database;
class MySQL
{
private $Host;
private $DBName;
private $DBTable;
private $DBUser;
private $DBPassword;
private $DBPort;
private $PDO;
private $parameters;
private $bConnected = false;
public $querycount = 0;
function __construct($DBName, $DBTable)
{
$this->Host = getenv("DATABASE_HOST");
$this->DBPort = getenv("DATABASE_PORT");
$this->DBUser = getenv("DATABASE_USER");
$this->DBPassword = getenv("DATABASE_PASSWORD");
$this->DBName = $DBName;
$this->DBTable = $DBTable;
$this->Connect();
$this->$parameters = array();
}
private function Connect()
{
try{
echo "I am the good child and always print".PHP_EOL;
$this->PDO = new PDO("mysql:host=localhost;port=33061;dbname=store", "root", "password");
echo "Please Print Me <3".PHP_EOL;
$this->bConnected = true;
} catch (PDOException $e){
echo $e->getMessage();
die();
}
}
I have checked values for Host, DBPort etc and in this code below I have all their values hard coded so nothing should be wrong due to the formatting of insert the variables in their proper slots. I know PDO is turned on because I can use it in other projects but my catch isn't catching anything, I can get the first echo to run but the second one never appears. Any help would be awesome because at this point I am scratching my head at why I can't get this to connect.
Thanks!
If I am unclear I can try and provide clarity and I can also show the driver file if need be but basically, it is just calling the constructor just fine and the connect function is giving us problems.

I have been going over each line of my code for about the last hour or so if not more. I found some discrepancies in my variables. I used in a couple places $this->$parameters
or other variations which didn't seem to cause an error for some reason but rendered the code inoperable. I'm not sure why it wasn't throwing an error about the variables but it would seem that is what caused my issue.
Thank you for your time and help!

Related

How can I stop this mysqli extension class from stopping executing on a failed 'real_connect'?

So the following code is in its infantile stages, and has a long way to go - but I am working on a database platform that is aware of multiple databases ( slaves, etc ), that is meant to attempt to open a connection to one, and upon failure, continue on to another. The relevant methods in the 'DatabaseConnection' class are as follows:
class DatabaseConnection extends mysqli
{
public function __construct($ConnectAutomatically=false,$Name="database",$Host="127.0.0.1",$Username="root",$Password="",$Catalog="",$Port=3306)
{
$this->CurrentHost = $_SERVER['SERVER_NAME'];
$this->Name = $Name;
$this->Host = $Host;
$this->Username = $Username;
$this->Password = $Password;
$this->Port = $Port;
$this->Catalog = $Catalog;
if( $ConnectAutomatically )
parent::__construct($this->Host, $this->Username, $this->Password, $this->Catalog, $this->Port);
else
parent::init();
return;
}
public function Open()
{
try
{
if(!parent::real_connect($this->Host,$this->Username,$this->Password,$this->Catalog,$this->Port))
{
return false;
}
else
return true;
}
catch( Exception $e )
{
return false;
}
}
}
The idea is that the database could be queried at any time, without having been initialized - therefore, the Query method checks for connectivity, and upon a lack thereof, runs the 'Open' method.
I have intentionally put a bad character in the password to force it to fail to connect, to see if it would connect to the second server in the list - but on the 'parent::real_connect' line, I am getting the obvious response that I cannot connect due to an invalid password.
I am wondering if there is a different approach I can take in this 'Open' method to NOT stop execution upon failure in the real_connect operation. I've taken a few swings at this and come up short, so I had to ask. It seems from my perspective that mysqli won't allow program execution to continue if the connect fails...
I have custom error catching already in place, which seems to catch the fault - but without interpreting the error and re-executing the DatabaseHandler connect method with the next in the list from Within my error handler, I don't see many other approaches at the moment.
I'll be glad to share more if need be.

OOP - Connecting to database via __construct [duplicate]

This question already has an answer here:
PHP: mysql_connect not returning FALSE
(1 answer)
Closed 8 years ago.
I'm very new to OOP and am trying to learn it. So please excuse my noobness. I'm trying to connect to mysql and to test whether the connection is successful or not, I'm using if-else conditions.
Surprisingly, the mysql_connect is always returning true even on passing wrong login credentials. Now I'm trying to figure out why it does and after spending about 20 minutes, I gave up. Hence, I came here to seek the help of the community. Here is my code:
class test
{
private $host = 'localhost';
private $username = 'root2'; // using wrong username on purpose
private $password = '';
private $db = 'dummy';
private $myConn;
public function __construct()
{
$conn = mysql_connect($this->host, $this->username, $this->password);
if(!$conn)
{
die('Connection failed'); // this doesn't execute
}
else
{
$this->myConn = $conn;
$dbhandle = mysql_select_db($this->db, $this->myConn);
if(! $dbhandle)
{
die('Connection successful, but database not found'); // but this gets printed instead
}
}
}
}
$test = new test();
Please don't use the mysql_* functions, there are many, many reasons why - which are well documented online. They are also deprecated and due to be removed.
You'd be much better off using PDO!
Also I'd strongly advise abstracting this database code into a dedicated database class, which can be injected where necessary.
On-topic:
That code snippet seems to work for me, have you tried var_dumping $conn? Does that user have correct rights?
I also hope that you don't have a production server which allows root login without a password!
Ignoring the fact that you're using mysql_* functions rather than mysqli or pdo functions, you should utilise exceptions in OOP code rather than die(). Other than that, I can't replicate your problem - it may be that your mysql server is set up to accept passwordless logins.
class test
{
private $host = 'localhost';
private $username = 'root2'; // using wrong username on purpose
private $password = '';
private $db = 'dummy';
private $myConn;
public function __construct()
{
// returns false on failure
$conn = mysql_connect($this->host, $this->username, $this->password);
if(!$conn)
{
throw new RuntimeException('Connection failed'); // this doesn't execute
}
else
{
$this->myConn = $conn;
$dbhandle = mysql_select_db($this->db, $this->myConn);
if (!$dbhandle)
{
throw new RuntimeException('Connection successful, but database not found'); // but this gets printed instead
}
}
}
}
try {
$test = new test();
} catch (RuntimeException $ex) {
die($ex->getMessage());
}

php two objects of the same database class. destruct failed to close database connection on second object

Sorry if the title of this question does not explain the actual question. I couldn't find appropriate word to name the title of this question.
I have a database class like so:
class Database
{
private $link;
private $host, $username, $password, $database;
public function __construct($setup)
{
if ($setup == 'default') {
$this->host = 'localhost';
$this->username = 'root';
$this->password = 'root';
$this->database = 'infobox_sierraleone';
}
if ($setup == 'promo') {
$this->host = 'localhost';
$this->username = 'root';
$this->password = 'root';
$this->database = 'infobox';
}
$this->link = mysql_connect($this->host, $this->username, $this->password)
OR die("There was a problem connecting to the database.");
mysql_select_db($this->database, $this->link)
OR die("There was a problem selecting the database.");
}
public function __destruct()
{
mysql_close($this->link)
OR die("There was a problem disconnecting from the database.");
}
}
I have created to different objects of the class above in a separate file:
include 'conn/database.php';
$db = new Database('default');
$db_promo = new Database('promo');
When i run the above script, i get this message:
There was a problem disconnecting from the database.
I realise that this message if from the __destruct() function.
I have researched for some time and i am still not clear why this message is showing and how to get rid of it.
Any sort of help will be much appreciated.
Thank You.
Edit:
removed the return statement that was in the constructor.
Since you're not destroying your own objects, they get destroyed by PHP when the script is finished. PHP then just destroys anything it's got, but not necessarily in the right order.
In this case, apparently PHP kills the MySQL connection first and then continues destroying other objects, including yours. Your object then tries to disconnect the already disconnected database connection, which would go unnoticed, if you wouldn't let the script die on failure.

"invalid data source name" with PDO MySQL

It was always working for me but this time it's not.
conect.ini
conn = "mysql:host=localhost; dbname=%dbname%"
user = "root"
pass = "%passwd%"
conn1 = "mysql:host=%myRealHostAddr%; dbname=%dbname%"
user1 = "%user%"
pass1 = "%passwd%"
pdo
class prepeared {
const LOG = "lock/loginsStat.log";
private $_db;
private $dbc;
function __construct(){
$this->dbc = parse_ini_file($_SERVER["DOCUMENT_ROOT"]."/hours/lock/conect.ini");
try{
$this->_db = new PDO($this->dbc["conn"], $this->dbc["user"], $this->dbc["pass"]);
}catch(PDOException $e){
echo $e->getMessage();
}
}
etc....
Vars %var% are real values just changed them for this post.
Vars with 1 are working at the hosting just fine (without 1, it was added only for a local testing). When I take it to a local machine for some testing I'm adding this 1 to disable them and making a new vars for a local settings.
The error that I see now it's
invalid data source name
Any ideas why? I know that this configuration was working just fine when I used it couple weeks ago so I suspect there is no errors here. Probably I'm wrong...
Get rid of catch(PDOException $e){ echo $e->getMessage();} stuff in order to get full and useful error message instead of that stub you have at the moment.
var_dump($this->dbc); also helps a lot.

Singleton holding multiple ADODB connections

A legacy website is exhibiting unexpected behavior with it's database connections. The application connects to several MySQL databases on the same server and the original developer created a "singleton" class that holds connection objects for each of them.
Lately we have been encountering a strange behavior with the class: when a connection to www is created after creating extra, getting the instance of extra returns a connection that has the correct parameters when viewed with var_dump() but is actually connected to the www database.
What could cause this? The code has worked before at some stage. Creating a new connection on each call to getInstance() fixes the problem but I'd like to solve this the right way if possible.
<?php
class DBConnection
{
private static $default;
private static $extra;
private static $intra;
private static $www;
public static function getInstance($dbname = "default")
{
global $db; // This is an array containing database connection parameters
if(!($dbname == "default" || $dbname == "extra" || $dbname == "www" || $dbname == "intra"))
{
$dbname = "default";
}
if (empty(self::$$dbname)) // Making this pass every time fixes the problem
{
try
{
self::$$dbname = ADONewConnection('mysqlt');
if(isset($db[$dbname]))
{
self::$$dbname->connect(DBHOSTNAME, $db[$dbname]["dbusername"], $db[$dbname]["dbpassword"], $db[$dbname]["dbname"]);
}
else
{
// fallback
self::$$dbname->connect(DBHOSTNAME, DBUSERNAME, DBPASSWORD, DBNAME);
}
self::$$dbname->SetFetchMode(ADODB_FETCH_ASSOC);
self::$$dbname->execute("SET NAMES utf8");
return self::$$dbname;
}
catch(Exception $e)
{
exit("DB connection failed");
}
}
else
{
return self::$$dbname;
}
}
}
Here's a simplified example of the class misbehaving:
$cn = DBConnection::getInstance("extra");
$cn->debug = true;
$rs = $cn->execute("SELECT * FROM messages WHERE id = ".$this->id);
The last line fails with the error message "Table www.messages does not exist".
1: You don't need to establish connection in getInstance().
getInstance must not do anything, but return instance of DB class.
2: when you do self::$$dbname->connect(, if (empty(self::$$dbname)) will return you false next time you call it.
Singleton is described here: http://en.wikipedia.org/wiki/Singleton_pattern
What you have - it's just a static method.

Categories