PDO unable to run query under Linux - php

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

Related

Error SQL Syntax

hi im rather new to SQL and im currently trying to save some data into a Sql database using a website. But everytime i run it i get some Syntax error and now after many hours of looking i was hoping somebody in here knew an answer, or could lead me in the right direction :)
this is the error i get when i hit my submit button :
0You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '[Campus one],[101],[2016-12-08],[test])' at line 1
this is the insert part of the script, connection part seems to be running fine
$sql = "INSERT INTO `formel`(`Område`, `Værelse`, `Dato`, `TV Fjernsyn Forlænger`) VALUES ([$area],[$filnavn],[$dato],[$Fjernsyn]) ";
SQL information:
Your values need to be changed from:
[$area],[$filnavn],[$dato],[$Fjernsyn]
to:
'{$area}','{$filnavn}','{$dato}','{$Fjernsyn}'
You should really be binding your params though. I assume you're using mysql_ which you shouldn't be using anymore therefore I also suggest you look into mysqli_ or PDO.
Edit:
You should move over to PDO in fairness, I did and I love it!
I work with classes a lot as it's a neater way to work so I'll give you my input:
Make yourself a dbConfig.php file:
class Database
{
private $host = "localhost";
private $db_name = "dbName";
private $username = "username";
private $password = "password";
public $conn;
public function dbConnection()
{
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
So because i am half lazy and why type code over and over?
Create yourself a dbCommon.php file.
class DBCommon
{
private $conn;
/** #var Common */
public $common;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
}
Then you need a class file for your PDO to go into such as:
class.update.php:
require_once('dbCommon.php');
class Update extends DBCommon
{
function __construct()
{
parent::__construct();
}
public function updateCode($area, $filnavn, $dato, $Fjernsyn)
{
$stmt = $this->runQuery("INSERT INTO `formel` (`Område`, `Værelse`, `Dato`, `TV Fjernsyn Forlænger`) VALUES (:area, :filnavn, :dato, :Fjernsyn)");
$stmt->bindParam(array(':area' => $area, ':filnavn' => $filnavn, ':dato' => $dato, ':Fjernsyn' => $Fjernsyn));
$stmt->execute();
echo "Your insert command has been completed!";
}
}
Then within your file.php where you would be calling the class you need to do:
require_once ('class.update.php');
$update = new Update();
if (isset($_POST['send']))
{
$update->updateCode($_POST['area'], $_POST['filnavn'], $_POST['dato'], $_POST['Fjernsyn']);
}
Note: Because you didn't post your $_POST['name']'s in I have given you a base example.
Binding your params is best practice as this prevents SQL Injection.
With binding params you dont have to run $stmt->bindParam(); You can simply run $stmt->execute(array(':paramshere' => $paramVar));
It totally depends on your preference but I always prefer binding before executing (personal preference). I hope this gives you some input and insight on how to move into PDO instead but it really is the way forward.
In order to prevent SQL injection, you should really use Prepared Statements, or correctly escape your strings. Please look at MySQLi or PDO.
Here's a basic tutorial using PDO and Prepared Statements inside of PHP:
// Connect to the database:
$db = new PDO( 'mysql:dbname=DB_NAME;host=localhost', 'DB_USER', 'DB_PASS' );
// Prepare the statement:
$ins = $db->prepare( 'INSERT INTO `formel` (`Område`, `Værelse`, `Dato`, `TV Fjernsyn Forlænger`) VALUES (:area, :filnavn, :dato, :Fjernsyn' );
// Execute with bindings:
$ins->execute(array(
':area' => $area,
':filnavn' => $filnavn,
':dato' => $dato,
':Fjernsyn' => $Fjernsyn
));
Try This,
$sql = "INSERT INTO `formel`(`Område`, `Værelse`, `Dato`, `TV Fjernsyn Forlænger`) VALUES ('$area','$filnavn','$dato','$Fjernsyn') ";
I think it should work.
Change your query to this
$sql = "INSERT INTO formel(Område, Værelse, Dato, TV Fjernsyn Forlænger) VALUES ('$area','$filnavn', '$dato', '$Fjernsyn') ";
But I would suggest you use prepared statement for security purposes

PHP DBlib PDO Issue

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());
}

What exactly a PDO statement will return when no rows match the query criteria?

I'm building a class to login users, so everything works great on localhost, but when i upload the files to the server, the code doesn't work as espected...
I checked this question Value return when no rows in PDO but i couldn't make it work...
My goal is to be able to retrieve the data from the Database and then check either the password is correct or not. I need 3 feedbacks:
User Doesn't exist
Pass/User combination doesn't match.
All good, proceed and login the user.
First I call the class:
$a = $login->login_user_admin($_POST['user']);
Then I get the result: Updated full class & connection
class Database extends PDO
{
private $dbname = "xxx";
private $host = "localhost";
private $user = "xxx";
private $pass = "xxx";
private $port = 5432;
private $dbh;
public function __construct()
{
try {
$this->dbh = parent::__construct("pgsql:host=$this->host;port=$this->port;dbname=$this->dbname;user=$this->user;password=$this->pass");
} catch(PDOException $e) {
echo $e->getMessage();
}
}
public function close_con()
{
$this->dbh = null;
}
}
class Users
{
private $con;
public function __construct()
{
$this->con = new Database();
$this->con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$this->con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
public function login_user_admin($user)
{
try{
$stmt = $this->con->prepare("SELECT name,salt,pass FROM users.users_admin WHERE name=? LIMIT 1");
$stmt->execute(array($user));
$this->con->close_con();
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo $e->getMessage();
}
}
}
Finally I process:
$data = [];
if ($a!=true) {
$data['success'] = false;
$data['message'] = 'User doesn't exist';
}else{
//All good proceed to chk the password.
}
I tried with empty and isset... didn't work on server either, they all work on local tough. I also try using fetchAll() and checking the empty string but i couldn't make it.
I went to check on the PHP versions on the server and local and they both running on 5.5 so I run out of ideas for now and I will appreciate some help on this.
Update!
I upload a file with only this code to check if I am getting any result from the database and I realize I am not,
include '../functions/functions.php';
$login = new Users();
$a = $login->login_user_admin("emirocast");
print_r($a);
var_dump($a);
The only user in the database right now is "emirocast" so i should get the result but i get a bool(false) instead.
The other thing I noticed is that the server is running Postgresql 8.4 and I am running 9.1 locally. Can this be the problem here?

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();
}
}
}

OOP: Function to check if value is in database

I'm trying to create a user management system class and one of my functions is to check if a value is in a column in the database. It returns nothing at all.
Here is the relevant information:
require("opperators/connect.php");
class UserManagemen
{
protected $db;
public function __construct(PDO $db)
{
$this->db = $db;
}
public function isInDatabase($checkIfThis, $isHere)
{
$stmt = $db->prepare("SELECT 1 from users WHERE $isHere = :$isHere");
$stmt->execute(array(':$isHere' => $checkIfThis));
if ($stmt->rowCount() > 0) {
echo "It's in the database";
} else {
echo "Not in the database and you are good to go!";
}
}
}
$usermanagement = new UserManagemen($db, null, null, null);
$usermanagement->isInDatabase(Batman, username);
in connect.php: this worked in my procedural coding test.
$configurator['database'] = array(
'username' => 'root',
'password' => 'root',
'host' => 'localhost',
'db' => 'girlscouts',
);
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
);
try {
$db = new PDO("mysql:host={$configurator['database']['host']};dbname={$configurator['database']['db']};charset=utf8", $configurator['database']['username'], $configurator['database']['password'], $options);
}
catch (PDOException $ex) {
die("Failed to connect to the database: " . $ex->getMessage());
}
I apologise in advance if this has been asked repeatedly, I've tried a google but returned nothing of value, possibly because I don't know what to google. I'm not big on asking for help but I'll give it a shot.
I think it should be
if ($stmt->rowCount() > 0) { // data available
echo "It's in the database";
} else {
echo "Not in the database and you are good to go!";
}
instead of
if ($stmt->rowCount() > 0) {
echo "Not in the database and you are good to go!";
} else {
echo "It's in the database";
}
Also you didn't initialize the PDO like new PDO(...);, in your constructor it should be
$this->db = new PDO(...);
and you should use it like
$stmt=$this->db->prepare(...);
$stmt->execute(...);
Take a look at this and this for details.
You are doing it wrong.
Instead of making additional request just to see, if such value already is stored in table, you should set UNIQUE constraint on column. Then, if you have correctly set up the PDO instance, the attempt to insert a duplicate will rise an PDOException, which then you can handle in whichever way you want.
Also the UNIQUE constraint would let you in MySQL perform .. ON DUPLICATE UPDATE .. construction.
To learn more about PDO use, read this tutorial. Seems like you are emulating the prepared statements.

Categories