Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

trouble populating class with MySQL data

5 views
Skip to first unread message

Anne Onime

unread,
Aug 12, 2010, 3:24:49 AM8/12/10
to
Greetings,

Specifically, I'm trying to reference a variable from an
include file I set up from within a class....

The include file (testdb.php) has:
$dbhost="localhost";
$dbuser="testdb";
$dbpass="x31X.23fw3f2";
$dbname="testDB";

And the class file has:
<?php

class myTestDB
{
function load_data()
{
require_once('./inc/testdb.php');

mysql_connect("$dbhost","$dbuser","$dbpass") or die("Unable to connect to Database");
print "db name is $dbname\n";
@mysql_select_db("$dbname");
print "dbname is $dbname\n";


When I run this method, it returns:
"db name is dbname is "


Even when I put the include or require clauses within the load_data() method the aforementioned variables
don't seem to be accessible.

This makes it obvious to me that the method, for whatever reason, isn't registering the
variables in the include file. If I do this on the top of the class file (myTestDB.class.php), the dbhost & dbuser & dbpass
variables are perfectly accessible. I guess my variable scope understanding is a bit rusty or
something. Can someone please shed some light on this situation?

Thank you in advance for your help!

Kevin Mooney

unread,
Aug 13, 2010, 9:19:30 AM8/13/10
to
Hi Anne,
PHP doesn't do global scope the way that most other languages do. So
you have to define the variables in your function as global.

Notice that in the revised code below, the first line of load_data()
is "global $dbhost, $dbuser, $dbpass;"

This tells PHP that you will reference those global variables from
within the function.


<?php
require_once('./inc/testdb.php');
class myTestDB
{
function load_data()
{
global $dbhost, $dbuser, $dbpass;

mysql_connect("$dbhost","$dbuser","$dbpass") or die("Unable to
connect to Database");
print "db name is $dbname\n";
@mysql_select_db("$dbname");


Cheers,
Kevin

0 new messages