tags:

views:

181

answers:

2

How can you have only one declaration of the database connection variable, $dbconn?

My login script is based on the following procedure

  1. If the user is not authenticated, he is thrown back to the login page
  2. If the user is authenticated, he gets an $_SESSION["logged_in"] = true;
  3. Then when the user is browsing the main page or other pages that need auth, they just check if the $_SESSION["auth"] is set.

I have the database variable only at the beginning of my index.php:

 $dbconn = pg_connect("host=localhost port=5432 dbname=masi user=masi password=123");

I do not the connection by db_close() anywhere in my codes. I source my login script to index.php which uses my database.

However, I get the standard warnings of not getting access to db when I do not have the variable declaration also in my scripts. If I add the declaration to each of my scripts, I get an access to db.

+1  A: 

We need to first understand how PHP is running the show here before we can delve into the wide, wide world of database connections.

Each PHP page request fires off a new PHP script. While you may have sessions turned on, that's an internal PHP construct only. The database sees this as a new connection/process connecting to the server. Therefore, it creates a new process on the database for it, so long as you call your pg_connect code. Otherwise, Postgres has no idea who you are or what session you want to use. Moreover, once the parent process dies, it generally kills the Postgres session (in this case, the PHP script runs and then dies once it's finished). Sometimes these can leave zombies roaming the streets of Postgres, but by and large, it'll just kill them.

If you want to use SQL code in your PHP script, you must connect to the database in that script before making a call to Postgres.

Eric
I just found out that one way to get the variable from the file which has the database -connection is to save the data from db to a variable which then can be passed as the parameter of the function to the second -file.
Masi
A: 

If i remember your other question you're redirecting to login.php? Which means that no the dbconn variable will not exist because it was initialised on another page.

if you required login.php from index.php it would work


$dbconn = pg_connect("host=localhost port=5432 dbname=masi user=masi password=123");
require_once('login.php');
rezzif
My experiment shows me that this fact cannot be true: I require login.php from index.php without having the $dbconn declaration twice in my codes - two warnings. To add the $dbconn variable to login.php seems to be necessary.
Masi
is login.php a class or a function? If so it won't have the required variable scope. unless you use global $dbconn; from within the function/class
rezzif
It is neither of them. I have the codes just in many php -files.
Masi