after reading a lot of post but not getting this thing running, maybe somone can help me with this.
I am trying to include a PHP (Module.php) file which craps information from db into my index.php. This index.php also includes the file with the database connection. The problem is the included file which handles the db selects seems not to know about the PDO Object, the Script dies which this error:
Fatal error: Call to a member function prepare() on a non-object in
I tried to make the PDO Object global. But unfortunately this is not working.
Thanks a lot for any help (and safe me not going crazy ...)
Tony
index.php
//DB Connection
require_once ("include/db_connect_inc.php");
$request = $_GET['Controll'];
switch ($request) {
case 0:
echo "XY";
break;
case 1:
global $objDb;
//This file should be able to use the DB Object
include("modules/Eat/Module.php");
break;
}
Module.php
global $objDb;
$dbSelect = $objDb->prepare(
"SELECT DISTINCT ON (nummer) nummer
FROM tableX
"
);
$dbSelect->execute();
while($row = $dbSelect->fetch(PDO::FETCH_ASSOC)) {
$all = $row['nummer'];
}
echo "1 - " . $all;
db_connect_inc.php
$strDbLocation = 'pgsql:host=localhost;dbname=test';
$strDbUser = 'root';
$strDbPassword = 'root';
try{
$objDb = new PDO($strDbLocation, $strDbUser, $strDbPassword);
$objDb->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$objDb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
global $objDb;
}
catch (PDOException $e){
//echo 'Fehler beim Öffnen der Datenbank: ' . $e->getMessage();
print "Error!: " . $e->getMessage() . "<br/>";
}
As you don't seem to use any functions, your variable is already set in the global scope, so you should get rid of all the global $objDb; lines.
That should solve the problem as long as there is no error in the first 3 lines where you connect to the database.
Apart from that I would use OOP / classes and use dependency injection to make sure my Module class is always provided with the stuff it needs (a db connection in this case).
Related
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...
This question already has an answer here:
How to use PDO connection in other classes?
(1 answer)
Closed 2 years ago.
Hello i am new to PDO with MYSQL, here are my two files
1) index.php
require_once 'prd.php';
try{
$db = new PDO ('mysql:host=xxxx;dbname=xxx;charset=utf8', 'xxx', 'xxxx');
echo 'connectd';
}catch(PDOException $conError){
echo 'failed to connect DB' . $conError->getMessage ();
}
$conn = new prdinfo();
$conn->con($db);
2) product.php
class prdinfo{function con($db){
try{
foreach($db->query("select * from products where vendor_id = 2" ) as $row){
$prod_id = $row ['product_id'];
echo '<br/>' . $prod_id;
}
}catch(PDOException $ex){
echo 'an error occured' . $ex->getMessage();
}
}
}
my problem is here i can pass the connection object to every file, but i have so many files to use database queries, so i need to pass the $bd to all the files. this is getting burden on the code. so is there any way to connect the database with PDO.
Thanks
pdo.php, taken from here. People often overlook many important connection options, so I had to write a dedicated article that explains how to connect with PDO properly
product.php
<?php
class prdinfo
{
function __construct($db)
{
$this->db = $db;
}
function getVendor($vendor)
{
$sql = "select * from products where vendor_id = ?";
$stm = $this->db->prepare($sql);
$stm->execute(array($vendor));
return $stm->fetchAll();
}
}
index.php
<?php
require 'pdo.php';
require 'product.php';
$info = new prdinfo($pdo);
$vendor = $info->getVendor(2);
foreach ($vendor as $row)
{
echo $row['product_id'];
}
It would be also a good idea to implement class autoloading instead of manually calling require.
The simplest way of doing it is to do the database connectivity in a separate file like "database.php and then you can include this file on every new page you are creating...eg if you are creating a page like "dothis.php". then at the top of your dothis.php page write a statement include_once ('/path/to/your/file/database.php');
then you can use your $db object in the whole file wherever you want.
What you can do is to create a PHP file, let's say 'pdoconn.php'. In that file, prepare that $db object. Finally, for each of your PHP files, just include pdoconn.php at first. So, while your PHP files are being loaded, they will firstly connect to MySQL and give you the $db object.
I need to do continuous parsing of several external stomp data streams, inserts of relevant fields into a MySql db, and regular queries from the db. All of this is in a protected environment - ie I'm not dealing with web forms or user inputs
Because I'm implementing a range of inserts into + queries from different tables, I've decided to set up a PDO active record model - following the advice of Nicholas Huot and many SO contributors.
I've got a simple repeated insert working OK, but after several days of grief can't get a prepared insert to fly. I want to use prepared inserts given there are going to be a lot of these (ie for performance).
Relevant bits of the code are :
=========
Database class :
private function __construct()
{
try {
// Some extra bad whitespace removed around =
$this->dbo = new PDO('mysql:host=' . DBHOST . ';dbname=' . DBNAME, DBUSER, DBPSW, $options);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
public static function getInstance()
{
if(!self::$instance)
{
self::$instance = new self();
}
return self::$instance;
}
public function prepQuery($sql) // prepared statements
{
try {
$dbo = database::getInstance();
$stmt = new PDOStatement();
$dbo->stmt = $this->$dbo->prepare($sql);
var_dump($dbo);
}
catch (PDOException $e) {
echo "PDO prepare failed : ".$e->getMessage();
}
}
public function execQuery($sql) // nb uses PDO execute
{
try {
$this->results = $this->dbo->execute($sql);
}
catch (PDOException $e) {
echo "PDO prepared Execute failed : \n";
var_dump(PDOException);
}
}
=========
Table class :
function storeprep() // prepares write to db. NB prep returns PDOstatement
{
$dbo = database::getInstance();
$sql = $this->buildQuery('storeprep');
$dbo->prepQuery($sql);
return $sql;
}
function storexecute($paramstring) // finalises write to db :
{
echo "\nExecuting with string : " . $paramstring . "\n";
$dbo = database::getInstance(); // Second getInstance needed ?
$dbo->execQuery(array($paramstring));
}
//table class also includes buildQuery function which returns $sql string - tested ok
=======
Controller :
$dbo = database::getInstance();
$movements = new trainmovts();
$stmt = $movements->storeprep(); // set up prepared query
After these initial steps, the Controller runs through a continuous loop, selects the fields needed for storage into a parameter array $exec, then calls $movements->storexecute($exec);
My immediate problem is that I get the error message "Catchable fatal error: Object of class database could not be converted to string " at the Database prepquery function (which is called by the Table storeprep fn)
Can anyone advise on this immediate prob, whether the subsequent repeated executes should work in this way, and more widely should I change anything with the structure ?
I think your problem in this line $dbo->stmt = $this->$dbo->prepare($sql);, php want to translate $dbo to string and call function with this name from this. Actually you need to use $this->dbo.
And actually your functions not static, so i think you don't need to call getInstance each time, you can use $this.
In anticipation of mysql_query being deprecated PHP 5.5.0, I have been working on a class to handle all my DB queries :
class DataBaseClass {
//.....some other function and variables declared here....
function GetConnection() {
try {
$this->conn = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
$this->conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
echo $e->getMessage();
}
return $this->conn;
}
function Query($str_sql, $arr_parameters = array()) {
try {
$this->str_mysql_error = $this->int_num_rows = $this->int_num_affected_rows = $this->int_mysql_insert_id = '';
if (count($arr_parameters) > 0) {
$obj_result = $this->conn->prepare($str_sql);
$obj_result->execute($arr_parameters);
} else {
$obj_result = $this->conn->query($str_sql);
}
}
catch(PDOException $e) {
$this->str_mysql_error = $e->getMessage() . $str_sql;
}
}
}
Then I have another class to create new user:
class AddNewUser {
//.....some other function and variables declared here....
function InsertUser() {
$str_sql = "INSERT INTO (uname, name, email, pass, user_regdate, theme) VALUES )";
$_SESSION['db_connection']->Query($str_sql, '');
}
}
Now on my main user creation page I have :
$_SESSION['db_connection'] = new DataBaseClass;
//Reason I used $_SESSION to store my DB object, is so that it can be accessible everywhere.
//Did not want to use "global" everywhere. Not sure if this is he best way???
$cls_new_user = new AddNewUser ();
$cls_new_user->InsertUser(); //Does not raise PDOExecption although SQL cleary wrong inside this method
if ( $_SESSION['db_connection']->str_mysql_error) {
//show error in error div
}
$str_sql = "SELECT some wrong SQL statment";
$_SESSION['db_connection']->Query($str_sql); // This does raise PDOExecption
if ( $_SESSION['db_connection']->str_mysql_error) {
//show error in error div
}
I'm not sure why the DB class function "Query" would not raise an exception on clearly wrong SQL when called from another class. But same function called from main page code (not inside function / class) raises and exception error.
Also, the "InsertUser" function does not execute / insert anything into DB even if SQL correct.
Could it be scope related, or the fact that I'm trying to enforce global scope of my DB object by putting it in $_SESSION ??
Am I going about this the wrong way? Reason for going class route to encapsulate all my DB calls was to avoid any deprecation issues in future - only having to update class.
Make your function this way.
function Query($str_sql, $arr_parameters = array()) {
$stmt = $this->conn->prepare($str_sql);
$stmt->execute($arr_parameters);
}
I am pretty sure that exception would be thrown
The only issue can be with catching exceptions, not throwing. And it could be caused by Namespace, not scope. To be certain, you can always prepend all PDO calls with a slash:
\PDO::FETCH_ASSOC
\PDOException
etc.
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