static php class and second mysql call

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jesbin
Forum Newbie
Posts: 1
Joined: Thu Apr 15, 2010 12:43 am

static php class and second mysql call

Post by jesbin »

I've a DataManager class which looks like the following

<?php

class DataManager {
protected static $link;
private static function _getConnection($dbname = 'wgexpert') {
if (isset(self::$link)) return self::$link;
self::$link = mysql_connect('localhost', 'root', '' );
$db = mysql_select_db('wgexpert') or die('Failure to access the database');
return (self::$link);
}

public static function getcountries() {
$sql = "call spGetCountries();";
$countries = array();
$result = mysql_query($sql, DataManager::_getConnection());
while ($row = mysql_fetch_array($result)) {
$countries[$row["countryID"]] = $row["countryName"];
}
return ($countries);
}

public static function getNominators($name, $org, $country) {
$sql = "call spSearchNominator('$name', '$org', $country);";
$res = mysql_query($sql, DataManager::_getConnection());
while ($row = mysql_fetch_array($res)) {
/ * do something */
}
}
}
?>


There there is a php page which calls two of the method of the class

require_once("classes/class.DataManager.php");
$data = DataManager::getcountries(); // first call
print_r($data);

DataManager::getNominators ("b", "", 0); //second call

If I call both of then I get the error while calling the second method. If I comment out one of them (any one), it is fine.
I cannot figure out what is going on. The same happens if I reverse the order of the call as well.

The error I get is for the second call (any method - always the second one):

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in D:\Program Files\EasyPHP-5.3.1\www\test\classes\class.DataManager.php on line 41

Basically, mysql_fetch_array($res) is failing because $res is null or empty.
I also discovered something else, if I destroy my static $link variable at the end of each method, it seems to work.

self::$link = null; // HAD TO DESTROY this for REASON UNKNOWN

This is however not a good solution.
Jesbin
Post Reply