I am trying to put all my database handling routines into a class (mysqldatabase). So far so good. I want to call one of the methods from this call one of the methods in this class from inside the function "selectTable()", but it responds with:
Fatal error: Call to a member function on a non-object in /var/www/html/database/listviews/listviews.php on line 60
(line 60 being the line indicated in the code)
So I tried the exact same code, but not in a function (the commented out block below) and it worked fine (it did have an issue with my close method mind you).
So my question is this: can methods be called from inside functions like this, or is there some scoping issue that I am missing?
Code: Select all
<?php
Require 'class_database.php';
function selectTable(){
// get table list from db and build select element from result
$HTMLselect = "<select>";
// *** the line won't work here ***
$tablelist = $MyDatabase->runquery("SHOW TABLES", "NUM");
foreach($tablelist as $key=>$value)
$HTMLselect .= "<option>$value[0]</option>";
$HTMLselect .= "</select>";
return $HTMLselect;
}
$MyDatabase = new mysqldatabase('localhost', 'mydatabase');
echo selectTable();
/*
// get table list from db and build select element from result
$HTMLselect = "<select>";
// *** the line works here ***
$tablelist = $MyDatabase->runquery("SHOW TABLES", "NUM");
foreach($tablelist as $key=>$value)
$HTMLselect .= "<option>$value[0]</option>";
$HTMLselect .= "</select>";
*/
$MyDatabase->close();
?>Code: Select all
<?php
class mysqldatabase {
var $host;
var $name;
var $link;
function mysqldatabase($hostname, $databasename){
$this->host = $hostname;
$this->name = $databasename;
// select database
$this->link = mysql_connect($this->host)
or die("Could not connect to host '$this->host': " . mysql_error());
mysql_select_db($this->name)
or die("Could not select database '$this->name':" . mysql_error());
}
function close(){
// close database
mysql_close($this->link);
}
function runquery($querystring, $returntype){
// run a query and return a 2d array of the results
$returntype = strtoupper($returntype);
if (($returntype !== 'ASSOC') and ($returntype !== 'NUM'))
$returntype = 'BOTH';
$queryresult = mysql_query($querystring)
or die('Query failed: ' . mysql_error());
$returnarray = array();
$linecount = 0;
while($line = mysql_fetch_array($queryresult, constant("MYSQL_$returntype")))
$returnarray[$linecount++] = $line;
return $returnarray;
}
}
?>Thanks in advance, Olly.