PHP DBlib PDO Issue - php

I am trying to connect to an MSSQL server through php but my pdo connection is giving me a hard time and errors that I don't really understand. The code I pasted below was working just fine a week ago and all of a sudden it just stopped without anyone changing anything. I can still connect to the server and run queries directly from the command line but I'm not having the same luck within php.
Anyone see something that I am missing? I spent too much time on this already and it seems like I'm running in circles.
First, this is the error I am getting from my PDOException
SQLSTATE[] (null) (severity 0)
Part of my Mssql()
private function __construct() {
try{
$this->_pdo = new PDO('dblib:host=' . Config::get('prod/host') . ':'. Config::get('prod/port') .';dbname=' . Config::get('prod/db'),Config::get('prod/username'), Config::get('prod/password'));
}catch(PDOException $e){
die($e->getMessage());
}
}
public static function getInstance(){
// Already an instance of this? Return, if not, create.
if (!isset(self::$instance)) {
self::$instance = new Mssql();
}
return self::$instance;
} //...This function is working and directs to __construct()
How I am calling it
/*Some random php file*/
function getClients(){
$conn = Mssql::getInstance();
//.....
And my init.php
//...
prod' => array(
'host' => 'xxxxxxx',
'port' => '1433',
'username' => 'xxxxxxx',
'password' => 'xxxxxx',
'db' => 'xxxxxxx'
),
//.....

We changed from using dblib to odbc and the code in my class changed to this:
private function __construct() {
putenv('ODBCSYSINI=/etc');
putenv('ODBCINI=/etc/odbc.ini');
$username = "xxxx";
$password = "xxxx";
try {
$this->_pdo = new PDO("odbc:production","$username","$password");
} catch (PDOException $exception) {
die($exception->getMessage());
}

Related

PHP new server connection method giving me errors [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 days ago.
Improve this question
I've been trying to fix the connection script for my site to make it more secure, by storing the login for the server nd all the details in a separate config file.
My intention was to just call this file for the login details on the server connection function using $this ->, but it's giving me the following errors:
Warning: Undefined property: Database::$server in C:\Program Files\xampp\htdocs\xampp\ecommerce1\includes\conn.php on line 21
Warning: Undefined property: Database::$username in C:\Program Files\xampp\htdocs\xampp\ecommerce1\includes\conn.php on line 21
Warning: Undefined property: Database::$password in C:\Program Files\xampp\htdocs\xampp\ecommerce1\includes\conn.php on line 21
Warning: Undefined property: Database::$options in C:\Program Files\xampp\htdocs\xampp\ecommerce1\includes\conn.php on line 21
I will post both versions of my script as I had it before when it was working, and as I have it currently.
Working(prior version)
<?php
Class Database{
private $config = "mysql:host=localhost;dbname=mysite";
private $config = "root";
private $config = "password";
private $config = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,);
protected $conn;
public function open(){
try{
$this->conn = new PDO($this->server, $this->username, $this->password, $this->options);
return $this->conn;
}
catch (PDOException $e){
echo "There is some problem in connection: " . $e->getMessage();
}
}
public function close(){
$this->conn = null;
}
}
$pdo = new Database();
?>
My attempt to update(broken code)
<?php
$config = include 'config.php';
Class Database{
public static function make($config)
{
try
{
return new PDO(
$config['connection'].':dbname='.$config['name'],
$config['username'],
$config['password'],
$config['options']
);
}
catch (PDOException $e){
echo "There is some problem in connection: " . $e->getMessage();
}
}
public function open(){
try{
$this->conn = new PDO($this->server, $this->username, $this->password, $this->options);
return $this->conn;
}
catch (PDOException $e){
echo "There is some problem in connection: " . $e->getMessage();
}
}
public function close(){
$this->conn = null;
}
}
$pdo = new Database();
?>
I don't understand why I can't store the login values on $this, like I did in the first example, is it because I'm calling these values from another file?
I thought I would include the config too just in case. Sorry for making this post so long
<?php
return [
'database' => [
'name' => 'db',
'username' => 'root',
'password' => 'password',
'connection' => 'mysql:host=localhost;dbname=db',
'options'=> [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]
]
]
?>

can't figure what might causing this error when creating PDO object

i am following a tutorial to create an OOP based login system.I did everything accordingly but while creating pdo i am getting an error in DB.php file in line 15.Can't figure out the reason for this error.Been stuck there for some time.Can anyone help me out with this error .The code might look long but it is a piece of cake for you i promise.There are FOUR php files.
1.init.php file holds the ingredients to create a new PDO() object.
2.config.php file is used to get data from init.php file as string is passed to it as ('mysql/host') type and use explode() function to extract data from it.
2.DB.php file is used to connect to database.
The error i am getting is
DB.php file:
class DB{
private $_instance=null;
private $pdo,
$query,
$error=false,
$results,
$count=0;
private function __construct(){
try{
$this->$pdo=new PDO('mysql:host='.Config::get('mysql/host').';dbname='.Config::get('mysql/db'),Config::get('mysql/user'),Config::get('mysql/password'));
}catch(PDOException as $e){
echo $e->getMessage();
}
}
public static function getInstance(){
if(!isset(self::$_instance)){
self::$_instance=new DB();
}
return self::$_instance;
}
}
Config.php file:
class Config{
public static function get($path){
if($path){
$config=$GLOBALS['config'];
$arr=explode('/',$path);
foreach($arr as $bit){
if(isset($config[$bit])){
$config=$config[$bit];
}
}
return $config;
}
}
}
init.php file:
session_start();
$GLOBALS['config']=array(
'mysql'=>array(
'host' => 'localhost',
'db' => 'login',
'user' => 'root',
'password' => ''
)
);
spl_autoload_register(function($class){
require_once 'c:/xampp/htdocs/login/classes/'.$class.'.php';
});
require_once 'c:/xampp/htdocs/login/function/sanitize.php';
index.php file:
require_once 'c:/xampp/htdocs/login/core/init.php';
DB::getInstance()->query('SELECT name FROM table WHERE id=1');
Your error message is a Parse Error. This means the PHP interpreter/processor/program tried to read your file, but found a syntax error, and had to stop. If you look at Line 15 of DB.php (per the error message)
}catch(PDOException as $e){
You'll see the problem. This isn't valid PHP syntax -- you probably want
}catch(PDOException $e){
The PDOException bit of that is a a class type hint for the exception handling code -- there's no need to use the as.

PDO no such file or directory - only ftp server access

I'm moving our php administration to a new server (hosted) but while trying out the migrated system, I detected that our code is unable to access the MySql database. The code was working before and the new webhost says it is supporting PDO. We have no ability to access the actual server more than via ftp and phpmyadmin, preventing us from accessing php.ini. We would prefer to be able to keep using PDO.
Any ideas how to fix this, and if not
How could we have this file working in the same/a similar way but without PDO?
Class Database{
protected $_link;
public function __construct(){
$config['db'] = array(
'hostname' => 'localhost', //The provided XXX.loopia.se and 127.0.0.1 has also been attemped here with no result
'dbname' => 'database_name',
'username' => 'user_name',
'password' => 'password'
);
$db = new PDO('mysql:hostname=' . $config['db']['hostname'] .';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
$this->_link = $db;
}
}
Log output:
PHP Warning: PDO::__construct() [pdo.--construct]: [2002] No such file or
directory (trying to connect via unix:///tmp/mysql.sock)
Link to loopia's "PHP to SQL"-use-this-code: https://support.loopia.se/files/php_till_mysql.zip
After quick feedback from the webhost, the above does not seem to be the preffered way to accomplish this at loopia. For further reference for other googlers, this is the code received (and edited to match the above purpose):
<?php
Class Database{
protected $_link;
public function __construct(){
$hostname = "xXXX.loopia.se"; //Log on to phpmyadmin and see what it says in the top after "server"
$username = "username";
$password = "password";
try {
$db = new PDO("mysql:host=$hostname;dbname=<DBNAME>",
$username,
$password,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$this->_link = $db;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
?>

PDO unable to run query under Linux

im trying to write OAuth class for VK to be able to authenticate users on my website. The problem i faced, is that the code i wrote on Windows, is not working at all on Linux.
I've successfully connected to my Linux Database through PHP->PDO script, but the problem is, that any function im trying to execute, im unable to get response or query, just nothing happening.
Here is the example of function:
Class Account
{
private $Connection;
private $ErrorHandler;
private $Template;
public function __construct()
{
global $DB, $Error, $Smarty;
$this->Connection = $DB->DBConnection;
$this->Template = $Smarty;
$this->ErrorHandler = $Error;
}
public function CheckDataWithVK($Username, $First_Name, $Last_Name, $Birth_Date)
{
$StatementHandler = $this->Connection->prepare("SELECT username,email,first_name,last_name FROM account WHERE username LIKE :username OR first_name LIKE :fname AND last_name LIKE :lname");
$StatementHandler->execute(array(':username' => $Username, ':fname' => $First_Name, ':lname' => $Last_Name));
$Result = $StatementHandler->fetch(PDO::FETCH_ASSOC);
if($Result['username'] == $Username)
{
$BuildUserNameArray = array('Username' => $Username, 'Email' => $Result['email'], 'Name'=> $Result['first_name'], 'Surname' => $Result['last_name']);
return $BuildUserNameArray;
}
else
{
if($Result['first_name'] == $First_Name && $Result['last_name'] == $Last_Name)
{
$BuildCredentialsArray = array('Username' => $Result['username'], 'Email' => $Result['email'], 'Name'=> $First_Name, 'Surname' => $Last_Name);
return $BuildCredentialsArray;
}
else
{
return false;
}
}
}
So on Windows, im able to get all the data and to check if user exists in database, but not on Linux.
Let me be selfish and say that im geek in this kind of thing, but even PDO returns no exceptions, so im unable to track flow of data and where error occurs.
I've already checked logs, but it seems that statement is not even executed...
Any help?
Thanks in advance
By the way, im using same classes on all my websites, and it is only one which behaves like this.... And yes, i tripple checked all settings, everything is correct.
Plus, im using:
$this->DBConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
So at least, if there is Exception, i should see something, but i see nothing -> no Exceptions
Here is my Database.Class.php:
public $DBConnection;
private $Template;
public function __construct($username, $password, $database)
{
global $Smarty;
$this->Template = $Smarty;
try
{
$this->DBConnection = new PDO("mysql:host=127.0.0.1;dbname=".$database, $username, $password, array(PDO::ATTR_PERSISTENT => true));
$this->DBConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
$message = $e->getMessage();
$this->Template->assign('ErrorHeader', $this->Template->getConfigVars('DatabaseError'));
$this->Template->assign('ErrorMessage', $e->getMessage());
$this->Template->Display('ErrorHandler.tpl');
echo "<!-- FreedomCore Servers: PDO Connection Error: $message -->\n";
die();
}
}
My bad, forgot to mention.... Idiot....
I'm able to insert values, but there is problem with this particular function
Problem was solved by updating server PHP Library to 5.5.12 version.
On Windows i've been using 5.5.5, on Linux 5.4.4, i think that what caused the problem

PHP designing OO database connection

So, I'm working on a project that requires a database connection. I've chosen to use PDO for its versatility and need to figure out how to set up the connection. Currently I'm going for something like this:
class Database {
private static $db;
static function initDB() {
if(!is_object(self::$db) || get_class(self::$db) != 'PDO') {
include('core/db.php');
try {
$db = new PDO($database, $username, $password);
} catch(PDOException $e) {
print("<br />Could not establish database connection. Error message: ".$e->getMessage()."<br />");
die();
}
}
//Try the transaction
/*
if($transaction = $db::query(PDO::quote($value)))
$db::query(PDO::quote("INSERT INTO log VALUES ('".Authorization::$user."','".PDO::quote($value)."', 'Success')"));
else
$db::query(PDO::quote("INSERT INTO log VALUES ('".Authorization::$user."','".PDO::quote($value)."', 'Failure')"));*/
}
}
So, this pretty much reveals one of the concepts I don't really know: singletons and static classes/objects. Any way to set up a database connection using OO best practices that initializes with the script via some kind of __construct method?
A database connection should not be either static or a singleton. This merely introduces another form of global state, which is bad for unit-testing and does hide obvious dependencies.
The right way here would be is to inject an instance of PDO into the classes that need it. You adhere the Single-Responsibility Principle and Dependency Injection.
Note, you should never log errors and do include() inside PDOAdapter constructor because its masked violation of the Single-Responsibility Principle
So, this would look like this:
final class PDO_Provider extends PDO
{
/**
* Constructor. Inits PDO
*
* #param array $params
* #return void
*/
public function __construct(array $params)
{
try {
extract($params);
parent::__construct(sprintf('mysql: host=%s; dbname=%s', $host, $database), $user, $password);
$this->setAttribute(parent::MYSQL_ATTR_INIT_COMMAND, 'SET NAMES UTF8');
$this->setAttribute(parent::ATTR_ERRMODE, parent::ERRMODE_EXCEPTION);
$this->setAttribute(parent::ATTR_EMULATE_PREPARES, false);
$this->setAttribute(parent::ATTR_DEFAULT_FETCH_MODE, parent::FETCH_ASSOC);
} catch(PDOException $e) {
die($e->getMessage());
}
}
}
And you would use it like this,
<?php
$sql_config = array(
'host' => 'localhost',
'user' => 'root',
'password' => '',
'database' => '_DB_NAME_',
);
// <- Or you can include that, like
$sql_config = include(__DIR__ . '/core/db_params.php');
$pdoProvider = new PDO_Provider($sql_config);
$user = new User_Login($pdoProvider); // the point here is to inject an instance of $pdoProvider. User_Login is actually irrelevant
if you want to use a normal object instead of sigleton, try something like this:
class PDOConnector{
protected $connection;
function __construct($host, $user, $pass, $db_name)
{
//create database connection
try{
$this->connection = new PDO('mysql:host='.$this->host.';dbname='.$this->db_name.';charset=utf8', $this->user, $this->pass,array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch(PDOException $ex) {
echo "An Error occured : ".$ex->getMessage();
}
}
}

Categories