Undefined variable with include or require - php

I'm trying to include a variable from a different file into my main php file but I keep getting Undefined variable.
accounts.php
# GUEST CREDENTIALS
$host = 'localhost';
$guestAccount = 'oncofinder';
$guestPassword = 'xxxxxx';
$database = 'oncofinder';
#LOGGER CREDENTIALS
$loggerAccount = 'logger';
$loggerPassword = 'xxxxx';
connections.php
function guestConnection() {
try {
require 'accounts.php';
$conn = new PDO("pgsql:host=$host;dbname=$database", $guestAccount, $guestPassword);
} catch (PDOException $e) {
echo "Error : " . $e->getMessage() . "<br/>";
die();
}
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
I tried to put my require in and out of my function but nothing works. I really thought this was straightfoward but I can't find an obvious solution.
Is there any thing I'm doing wrong? Isn't this the procedure?
Regards

I think you have variables defined in global scope but you try to use it in local scope.
To confirm naming scope issue try to:
require 'accounts.php';
function guestConnection() {
global $host, $database, $guestAccount, $guestPassword;
try {
$conn = new PDO("pgsql:host=$host;dbname=$database", $guestAccount, $guestPassword);
...
This should work if your guestConnection() is in global scope not under any namespace or class.
or do move require out of try to get errors if any (file does not exist?):
function guestConnection() {
require('accounts.php');
try {
$conn = new PDO("pgsql:host=$host;dbname=$database", $guestAccount, $guestPassword);
...

I had a similar problem on my CentOS server. Try using the full absolute path (server conf might not be configured to allow calling of same-level files this way):
require_once $_SERVER['DOCUMENT_ROOT']. '/path/to/accounts.php';
Note:
you can use require and it should still work. I just think require_once is safer (in terms of not accidentally duping code).

Related

How to execute more than one statement in try command

I am trying to establish a PDO connection using the try block and then printing a success message after the connection gets established. My code is as follows:
index.php :
<?php
require_once './vendor/autoload.php';
$con = new \app\db\Connect();
if ($con)
{
echo 'connection successful.';
}
connect.php
<?php
namespace app\db;
class Connect
{
public function __construct()
{
// set the connection variables
$host = 'localhost';
$dbname = 'pdoposts';
$username = 'root';
$password = 'root';
// create the DSN
$dsn = 'mysql:host=' . $host . ';dbname=' .$dbname;
// create PDO connection
try {
static $con;
$con = new PDO($dsn, $username, $password);
} catch(Exception $e) {
echo $e->getMessage();
}
return $con;
}
}
My problem is that there is no way for me to use the $concreated in the try - catch command in the index.php file. I am very sorry if this question seems very basic and elemental one, but please help me understand how it can work. Thank you very much in advance.
Accoring to the answer below:
The solution here on stackoverflow
I just added the backslash right before PDO and made it to be \PDO and it is now working properly. The link below can help understanding PHP Callbacks and how they work better:
Using namespaces: fallback to global function/constant
I should have kept in mind the namespace from which I wanted to use PDO from. In this case, using a \ would tell php to use PDO from the Global Namespace and not from the namespace from which the code runs in (app\db).

Symfony 1.4 project in SAAS mode - multiple databases

I have a Symfony 1.4 project that I want to use in SAAS mode for multiple customers.
The idea is to have multiple domains and databases but to always use the same code. I also don't want to have to change anything in my project for each new customer : everything must be dynamic.
I've been trying for a few hours now to override the database.yml configuration but it wasn't really a success. I added at the beginning of my ProjectConfiguration.class.php :
require_once '/path/to/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine.php';
spl_autoload_register(array('Doctrine', 'autoload'));
$manager = Doctrine_Manager::getInstance();
$serverName = $_SERVER['SERVER_NAME'];
if(preg_match("#\.saas-domain\.com$#", $serverName))
$dbname = "db-" . preg_replace("#\.saas-domain\.com$#", "", $serverName);
else
$dbname = "db-default";
$dsn = "mysql:dbname=$dbname;host=localhost";
$user = 'dbuser';
$password = 'dbpsw';
try {
$dbh = new PDO($dsn, $user, $password);
$conn = Doctrine_Manager::connection($dbh);
} catch (PDOException $e) {
die("Can't find that database");
}
I tried to put this code at the end of the setup() method, same thing : it doesn't seem to be used.
As you can see I wanted to deduce the database to use from the domain (ServerName in apache).
My very last option is to manually alter each config_database.yml.php file generated in cache (in fact only alter one and use symlinks), but I really would like not to have to do this.
So my questions are :
Is it possible to override the database.yml configuration ?
If not, is there a way I can delete this file or ignore it and set up a manual doctrine configuration ?
Are there any other solutions that I didn't consider ?
EDIT
I managed to come up with a solution (with the help of this article). It's probably not the best way to do it, but at least the result is OK.
The idea is to use Symfony's filters in order to replace the connection created by the database YAML file :
In config/filters.yml add the following :
myDBConnectionFilter:
class: myDBConnectionFilter
Then create this myDBConnectionFilter class and put it anywhere it can be found by Symfony's autoloader (lib in most cases). Below is an example of code you can use in this class :
<?php
class myDBConnectionFilter extends sfFilter
{
public function execute($filterChain){
if ($this->isFirstCall())
{
$serverName = $_SERVER['SERVER_NAME'];
if(preg_match("#\.saas-domain\.com$#", $serverName))
$dbname = "db-" . preg_replace("#\.saas-domain\.com$#", "", $serverName);
else
$dbname = "db-default";
$dsn = "mysql:dbname=$dbname;host=localhost";
$user = 'user';
$password = 'password';
$manager = Doctrine_Manager::getInstance();
try {
$default = $manager->getConnection('dbconnection');
Doctrine_Manager::getInstance()->closeConnection($default);
$dbh = new PDO($dsn, $user, $password);
$conn = Doctrine_Manager::connection($dbh, 'dbconnection');
} catch (Exception $e) {
die("Error : " . $e->getMessage());
}
}
$filterChain->execute();
}
}
You'll then need to clear Symfony's cache.
This code retrieve a connection from Doctrine_Manager, close it, then create a new one with the same name to replace it. In this case, the connection is called dbconnection. The name of the connection is the one used in database.yml.
As I said, it is not the best way to do it as this method makes two connections to the database instead of one. So if anyone has a better solution i would take it !

DB connections. SQL retrieve error

I define all my connections on an external file called db_config.php
This enables my class files to use db_config.php file for connections.
However, I am wondering if someone could shed some light on the following error.
SQL Retrieve Error: No database selected
This is referring to this line of code on db_config.php.
return array("host"=>"x", "username"=>"x", "password"=>"x", "dbname"=>"x" );
This is the function that makes the call
function openDB() {
$config = include_once("assets/configs/db_config.php");
$conn = mysqli_connect(
$config["host"] , $config["username"],
$config["password"], $config["dbname"]);
$this->conn = $conn;
return true;
}
What am I missing?
First of all make sure the variables in the config file are correct. If they are correct the try changing the include_once to include.
if that is not working, then change the code to :
function openDB() {
$config = array("host"=>"x", "username"=>"x", "password"=>"x", "dbname"=>"x" );
$conn = mysqli_connect(
$config["host"] , $config["username"],
$config["password"], $config["dbname"]);
$this->conn = $conn;
return true;
}
See if this works my way. If it does then your won't need the db.php file.
Please dump the $config variable and check what is going wrong ,
<?php
var_dump($config);
?>
So you can find $config is returning an array or not !

Prblems with setting PDO connection global

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).

Is require/include, in multiple files, necessary if they are all part of the same namespace?

I am brand-spanking-new to the namespace concept in php.
The situation:
Multiple files in a folder and they all require/include one another for their own purposes.
If i were to place them all in the same namespace, would it still be necessary to have them require/include each other?
I did think of replacing the require/include with "use", but it seems odd to have a file in namespace foo\bar to actually 'use' foo\bar... o_O
PS:
I am covering all my bases by asking questions while also searching the net for answers; so if you have any good sources for info/tutorials etc please feel free to share. :D
Thank you,
David
It can get messy with all the includes/requires. The included files on one included file, will be also included on the first one as well, with out explicitly calling it. I would suggest, if you are using OOP approach, start out using the __autoload() magic method. This will save you tons of headaches down the road when you include a file on a page that's already been included elsewhere running on that page and you get a 500 server error because of it.
Yes, you have to require them, or you can use a psr-0 compatible autoloader
If i were to place them all in the same namespace, would it still be necessary to have them require/include each other?
You can create a loader class for example (it's what I always do, so you only have to include/require them once, and you only have to include/require the loader class in your controller). Here is the current one I'm using:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
//include alle classes
include("classes/db.class.php");
include("classes/gastenboek.class.php");
include("classes/gebruiker.class.php");
include("classes/bericht.class.php");
session_start();
$db = new Db();
//require smarty (smarty template engine)
require('plugins/smarty/Smarty.class.php');
$smarty = new Smarty;
$smarty->setCompileDir('smarty_compile');
$smarty->setTemplateDir('templates');
//func to dump var
function dump($var)
{
//echo ##
echo '<pre>##';
//print var
print_r($var);
//echo ##
echo '##</pre>';
}
With db.class being this for example:
<?php
class Db
{
//Loading Db
public function __construct()
{
//do connect()
$this->connect();
}
//connecting and selecting db
private function connect()
{
$connection = mysql_connect('localhost', 'user', 'pw');
if(!$connection)
{
die("Kan geen verbinding maken: " . mysql_error());
}
mysql_select_db("db", $connection);
}
public function DBH()
{
try
{
$DBH = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'pw');
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $DBH;
}
catch (PDOException $except)
{
echo $except->getMessage();
}
}
index.php would then only need this:
include("includes/loader.php");

Categories