...

View Full Version : variables lifespan dblink in class



Exodious
11-09-2003, 08:03 PM
Hiya, I've created a class to manage my database stuff (first go at php really), and on instantiating the class, open the database using the constructor and args passed in.

If I then try and execute an sql statement using my deptly named sql function, all is well, but the dblink variable is empty, so can't use mysql_close to close the connection...

Any ideas?

mordred
11-09-2003, 08:09 PM
Hard to say what's going on without seeing a test case that exhibits the described behaviour. In other words - post some code. :)

Exodious
11-09-2003, 08:24 PM
class dbtest
{
var $dbLink;
var $dbName;
var $host;
var $user;
var $pwd;

var $resultSet;

var $tableArr;
//var $hasData = false;

var $numColumns;
var $numRows;

# constructor
function dbaccess($h, $u, $p, $n)
{
$host = $h;
$user = $u;
$pwd = $p;
$dbName = $n;

$dbLink = mysql_connect($h, $u, $p) or die("Could not connect: " . mysql_error());
print "<br>Database successfully opened";

mysql_select_db($n) or die("<br>Could not select database: " . $n);
print "<br>Database: <b>" . $n . "</b> selected";

}

function sql($sqlStr)
{
$resultSet = mysql_query($sqlStr) or die("<br>Query failed: " . mysql_error());
$numRows = mysql_num_rows($resultSet);
$numColumns = mysql_num_fields($resultSet);

$tableArr = array($numRows => array($numColumns));

$i = 0;
$rowID = 0;

print "<br>numRows: " . $numRows . " - numColumns: " . $numColumns . " - dbLink: [" . $dbLink . "]";

# fill tableArr
while ($row = mysql_fetch_array($resultSet, MYSQL_ASSOC))
{
for($i=0; $i<$numColumns; $i++)
{
//print "<br>Table/col val: [" . $row[$i] . "] - rowID: " . $rowID . " - i: " . $i . " - count(arr): " . count($tableArr);
$tableArr[$rowID][$i] = $row[$i];
}
$rowID++;
$hasData = true;
}

mysql_free_result($resultSet);

print "Table arr value 1: [" . $tableArr[0]
[1] . "]";

mysql_close($dbLink); // no dbLink is the error this gives and its right, tis null

}
}


$obj = new dbtest(host, username, pwd, tablename);
$obj->sql("select * from table where id=1");

mordred
11-10-2003, 12:10 AM
You are not storing the db link as an object's property. Use this code:



$this->dbLink = mysql_connect($h, $u, $p) or die("Could not connect: " . mysql_error());


and later this



mysql_close($this->dbLink);

Exodious
11-10-2003, 11:44 AM
That would also apply to the tableArr then, ah ha, me so much more knowledgable now :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum