多次调用PHP函数会产生MySQL错误

I'm trying to retrieve multiple data from a database with a PHP function, but somehow when I do this multiple times it gives a MySQL connection error.

$heat=getStat("heat", $userid);
$cash=getStat("cash", $userid);
echo mysql_error();

I use the code above to assign variables by calling a function which retrieves the stats from a database.

When I use the above codes separately, they work. But when I put them together they fail.

Is this a simple you-are-a-beginner-noob-programming-mistake?

I forgot to post the function so here it is:

function getStat($statName,$userID) {
    require_once 'config.php';
    $conn = mysql_connect($dbhost,$dbuser,$dbpass)
       or die('Error connecting to MySQL' . mysql_error());
    mysql_select_db($dbname);
    $query = sprintf("SELECT value FROM user_stats WHERE stat_id = (SELECT id FROM stats WHERE display_name = '%s' OR short_name = '%s') AND user_id = '%s'",
    mysql_real_escape_string($statName),
    mysql_real_escape_string($statName),
    mysql_real_escape_string($userID));
    $result = mysql_query($query);
    list($value) = mysql_fetch_row($result);
    return $value;        
}

Test for the success of the first call to that function, before you move on to the next call. Calling them contiguously - without waiting for the result of the other - may not catch any errors. You have to wait for and react to the server response from your call to the database.

Confirm your call to the database - then move on to call the function again. Never just blindly query a database without the ability to catch and react to errors.

if($heat=getStat("heat", $userid)){
       $cash=getStat("cash", $userid);
    }

Retrieve one - wait/test for results - retrieve the other.

The problem is most likely caused by the require_once. As this is where you are pulling in your config for the database connection. The second time the require is executed it will not pull in the code required to define your database connection vars.

As @MichaelBerkowski has stated, it would be much better to have one global connection when the script loads, and make use of this connection for each request to the database. However if you wish to stick with the way you have currently, this should solve the problem:

function getStat($statName,$userID) {
    require 'config.php'; /// <-- note this has changed to just require
    $conn = mysql_connect($dbhost,$dbuser,$dbpass)
        or die ('Error connecting to mysql');
    mysql_select_db($dbname);
    $query = sprintf("SELECT value FROM user_stats WHERE stat_id = (SELECT id FROM stats WHERE     display_name = '%s' OR short_name = '%s') AND user_id = '%s'",
        mysql_real_escape_string($statName),
        mysql_real_escape_string($statName),
        mysql_real_escape_string($userID));
    $result = mysql_query($query);
    list($value) = mysql_fetch_row($result);
    return $value;      
}