Calling a PHP function several times creates a MySQL error

I'm trying to get some data from a database using a PHP function, but for some reason, when I do this several times, you get 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 that retrieves statistics from the database.

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

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

I forgot to publish the function, 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; } 
+6
source share
2 answers

The problem is most likely caused by require_once . Since you are trying to connect to your configuration to connect to the database. The second time the requirement is met, it will not pull the code necessary to determine your database connections.

As @MichaelBerkowski stated, it would be much better to have one global connection when loading a script and use that connection for every query in the database. However, if you want to stick with what you currently have, 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; } 
+5
source

Verify the success of the first call to this function before proceeding to the next call. Calling them contiguously - without waiting for the result of another - may not catch any errors. You need to wait and answer the server response from your call to the database.

Confirm your call to the database - then go to the function call again. Never blindly access a database without being able to catch and respond to errors.

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

Get one - wait / check results - get another.

-2
source

Source: https://habr.com/ru/post/980815/


All Articles