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.
Related
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!
I've been trying to use a sqlite database (php with PDO), but have been running into a problem. Generally the commands work, and everything is fine (including storing files), but for some reason when I run these two commands (which have been simplified), I get the error
SQLSTATE[HY000]: General error: 5 database is locked
I've tried for a while, but have been unable to fix whatever is wrong. The code is below.
Things I've done:
Tried to put sleep(2) between commands
Found out that commenting either of the commands out will cause the error not to happen (which doesn't really help, as both commands must run)
Note that (unlike other problems I saw while looking at similar questions) the database operates correctly in other cases.
$db = new MyDB();
$STH = $db->catchMistakes('SELECT PASSWORD FROM USERS WHERE USERNAME = ?', "test");
$STH->fetchColumn();
$db->catchMistakes("UPDATE ISSUES SET NAME = ? WHERE NUM = ?", ["test", "1"]);
And here's the code for MyDB
public function catchMistakes($cmd, $params = []) {
if (!is_array($params)) {
$params = [$params];
}
try {
$DBH = new PDO("sqlite:" . DB);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$DBH->beginTransaction();
$query = $DBH->prepare($cmd);
$toReturn = $query->execute($params);
$DBH->commit();
return $query;
}
catch(PDOException $e) {
$DBH->rollback();
$error = $e->getMessage();
exit;
}
}
Sorry if there's a simple fix, I'm pretty new at this. Any help would be greatly appreciated.
You can use closeCursor() method on a PDOStatement object to free the connection to the database so the statement can be executed. You can refer to the PHP manual.
For the last two days, I've been struggling with a very strange bug while I'm connecting with Vertica using PDO. You see, the following script works:
$c = new PDO("odbc:Driver=Vertica;Server=x.x.x.x;Port=5433;Database=db;", "MyUser", "MyPassword");
$c->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $c->prepare("SELECT * FROM myClients WHERE ClientNum = 88");
$stmt->execute();
After that, I loop through the results and display them no problem. This basically means my connection is correct otherwise I wouldn't get anything out of the database. On the other hand, the following makes the Apache server reset the connection completely (when run in Windows, I get a message that Apache crashed):
$c = new PDO("odbc:Driver=Vertica;Server=x.x.x.x;Port=5433;Database=db;", "MyUser", "MyPassword");
$c->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$c->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
//$c->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
try
{
$stmt = $c->prepare("SELECT * FROM myClients WHERE ClientNum = :cl");
$stmt->bindValue(":cl", 88);
$stmt->execute();
while($res = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $res['noClient'] . "<br>";
}
}
catch(Exception $e)
{
echo $e->getMessage();
}
The problem is present both in Linux and Windows and I'm using Vertica version 7.0.2-1 along with the corresponding ODBC driver. The problem was also present in Vertica 6.1. Can anyone give me a hand with this?
Thanks in advance.
EDIT: I tried to set PDO::ATTR_EMULATE_PREPARES to both true and false without any change.
EDIT: This being a test script, I didn't bother with any error handling. Also, given that the server actually crashes, I doubt it would change anything.
EDIT: Updated the code above to include some basic error handling. Apologies to Kermit for sounding condescending in my earlier comment. Anyway, even with this addition to my code, I still didn't get any message, the server would just silently crash and I'd get a "Connection reset" page. Upon seeing this, I tried querying different tables in my database and on one, instead of a crash, I got the following:
SQLSTATE[HY000]: General error: 50310 [Vertica][Support] (50310) Unrecognized ICU conversion error. (SQLExecute[50310] at ext\pdo_odbc\odbc_stmt.c:254)
EDIT: Went to my ODBC DSN, clicked Configure, went on the Server Setting tab and found that the locale was set to: en_US#collation=binary (which is the default for Vertica, I believe). Should I check somewhere else?
EDIT: I was curious to see what the bindValue() was doing to my query and so opened the vertica.log file. Here's what I saw:
2014-10-02 11:38:42.100 Init Session:0x5ef3030 [Session] <INFO> [Query] TX:0(vertica-1756:0xbc42) set session autocommit to on
2014-10-02 11:38:42.104 Init Session:0x5ef3030 [Session] <INFO> [PQuery] TX:0(vertica-1756:0xbc42) SELECT * FROM myClients WHERE ClientNum = ?
2014-10-02 11:38:42.105 Init Session:0x5ef3030-a00000000aac68 [Txn] <INFO> Begin Txn: a00000000aac68 'SELECT * FROM myClients WHERE ClientNum = ?'
2014-10-02 11:38:42.915 Init Session:0x5ef3030-a00000000aac68 <LOG> #v_flexgroup_node0001: 08006/2895: Could not receive data from client: No such file or directory
2014-10-02 11:38:42.915 Init Session:0x5ef3030-a00000000aac68 <LOG> #v_flexgroup_node0001: 08006/5167: Unexpected EOF on client connection
2014-10-02 11:38:42.915 Init Session:0x5ef3030-a00000000aac68 <LOG> #v_flexgroup_node0001: 00000/4719: Session vertica-1756:0xbc42 ended; closing connection (connCnt 2)
2014-10-02 11:38:42.916 Init Session:0x5ef3030-a00000000aac68 [Txn] <INFO> Rollback Txn: a00000000aac68 'SELECT * FROM myClients WHERE ClientNum = ?'
Apparently, it seems PDO is replacing the placeholders by question marks in the final query. Not all that unexpected, but for some reason, the actual value of the parameter seems to get lost along the way.
EDIT: Following a suggestion, I tried:
$stmt = $c->prepare("SELECT * FROM myClients WHERE ClientNum = :cl");
$stmt->execute(array(":cl" => 88));
But the problem remains the same.
Okay, so after going halfway crazy trying to figure out what was wrong with PDO, I discovered that using PHP odbc module directly worked.
Since all my modules are actually written using PDO and rewriting them was not an option, I ended up writing the following wrapper classes:
class PDOVertica
{
protected $conn;
public function __construct($dsn, $user, $password)
{
$this->conn = odbc_connect($dsn, $user, $password);
}
public function prepare($qry)
{
return new PDOVerticaStatement($this->conn, $qry);
}
public function lastInsertId()
{
$stmt = odbc_prepare($this->conn, "SELECT LAST_INSERT_ID()");
odbc_execute($stmt);
$res = odbc_fetch_array($stmt);
return $res['LAST_INSERT_ID'];
}
}
class PDOVerticaStatement
{
protected $qry;
protected $param;
protected $stmt;
public function __construct($conn, $qry)
{
$this->qry = preg_replace('/(?<=\s|^):[^\s:]++/um', '?', $qry);
$this->param = null;
$this->extractParam($qry);
$this->stmt = odbc_prepare($conn, $this->qry);
}
public function bindValue($param, $val)
{
$this->param[$param] = $val;
}
public function execute()
{
if($this->param == null)
odbc_execute($this->stmt);
else
odbc_execute($this->stmt, $this->param);
$this->clearParam();
}
public function fetch($option)
{
return odbc_fetch_array($this->stmt);
}
protected function extractParam($qry)
{
$qryArray = explode(" ", $qry);
$ind = 0;
while(isset($qryArray[$ind]))
{
if(preg_match("/^:/", $qryArray[$ind]))
$this->param[$qryArray[$ind]] = null;
++$ind;
}
}
protected function clearParam()
{
$ind = 0;
while(isset($this->param[$ind]))
{
$this->param[$ind] = null;
++$ind;
}
}
}
I was pleasantly surprised to find that this works without me having to rewrite hundreds of modules. I do need to rework some of the SQL since there are differences between MySQL and Vertica, but those are just minor touch ups.
Anyway, should anyone choose to use these classes, keep in mind I only implemented what I needed in terms of functionalities and they only work with queries using placeholders for parameters (:someParameter). Use them and modify them at your own discretion.
Thanks for anyone who helped me.
I'm having problems accessing my PHP backend from AngularJS.
I have followed:
http://coenraets.org/blog/2012/02/sample-application-with-angular-js/
Routing with AngularJS and Slim PHP
Some other's too but those are similar. I've tackled the problem for a few days now and still can't get it working.
First way to call my php script
app.controller('PhoneDetailCtrl',function($scope, $modal, $resource) {
var request_Id = 1;
var Request = $resource('http://mobiiltelefonid24.ee/api/kasutatud_telefonid/'+request_Id);
$scope.request = Request.get();} //this way I get code 200 but 119 empty chars.. So I figure routing should be correct?
Second way I tried
app.controller('PhoneDetailCtrl',function($scope, $modal, Service) {
$scope.request = Service.get({id:1});} //this gives me code 200 but 119 empty chars...
app.service('Service', function ($resource) {
return $resource('api/kasutatud_telefonid/:id', {}, {
update: {method:'PUT'}
});});
PHP code (using mysql db)
require 'Slim/Slim.php';
$app = new Slim();
$app->get('/', 'getPopularPhones');
$app->get('/uued_telefonid','getNewPhones');
$app->get('/kasutatud_telefonid','getUsedPhones');
$app->get('/uued_telefonid/:id', 'getPhoneDesc');
$app->get('/kasutatud_telefonid/:id', 'getPhoneDesc');
$app->run();
/*Other get methods are exactly the same but with different name*/
function getPhoneDesc($id) {
$sql = "SELECT * FROM Phone";
try {
$db = getConnection();
$stmt = $db->query($sql);
$wines = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($wines);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
getConnection() is implemented as shown in wine app tutorial. There is one row in db that has 21 colums so it should return something. Also tried to pass string $wine="teststring" but that also arrived as jibbrjabbre.
Is routing wrong or is there problems with querying from db? (I can query just fine from phpMyAdmin). Out of ideas...
Solved! Slim was falsely configured and meekroDB worked just fine (Thanks mainguy). On top of that there were some issues on webhosts side.
For some reason, this custom PDO class fails to write to the database. It simply quietly fails - no error message thrown. A very similar custom PDO class (ReadPDO) works wonderfully for reading from the database. The SQL statement generated works fine when it's queried to the DB through PHPMyAdmin. I've double-checked the user permissions, and everything seems in order.
I suspect I'm misunderstanding how something works. Any ideas?
// Creates a write-only PDO, using config settings from inc_default.php
class WritePDO extends PDO{
public function __construct(){
//Pull global DB settings
global $db;
global $write_host;
global $write_username;
global $write_password;
try{
parent::__construct("mysql:dbname={$db};host={$write_host}", $write_username, $write_password);
} catch (PDOException $e){
echo 'Connection failed: ' . $e->getMessage();
}
}
}
private function updatePlayer(){
$conn = new WritePDO();
$sql = "UPDATE {$this->hvz_db}
SET
hvz_bitten ='{$this->hvz_bitten}',
hvz_died ='{$this->hvz_died}',
hvz_feedCode ='{$this->hvz_feedCode}',
hvz_status ='{$this->hvz_status}',
hvz_feeds ='{$this->hvz_feeds}',
hvz_lastFed ='{$this->hvz_lastFed}',
hvz_ozOpt ='{$this->hvz_ozOpt}',
hvz_parent ='{$this->hvz_parent}'
WHERE users_id ={$this->id}";
$query = $conn->exec($sql);
}
The SQL it spits out is as follows:
UPDATE hvz_2011_spring SET hvz_bitten ='', hvz_died ='', hvz_feedCode ='NOMNOM', hvz_status ='Human', hvz_feeds ='0', hvz_lastFed ='', hvz_ozOpt ='0', hvz_parent ='' WHERE users_id =1
are you sure the sql is correct?
The exec doesn't send any error message.
Try doing var_dump($conn->errorInfo()); after $conn->exec($sql);
/Emil