Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a PHP function multiple times creates MySQL error

Tags:

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;        
}
like image 746
Mark Avatar asked Jan 10 '15 23:01

Mark


1 Answers

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;      
}
like image 194
Pebbl Avatar answered Nov 08 '22 19:11

Pebbl