PHP 5.2 mysql_connect w/ same parameters does not return a new connection!

This is subtle… I was writing some “reconnect” logic for a DB Class to catch and handle MySQL error code 2006, Server Gone Away. After a solid 5 hours of wasted time I traced the poor logic on my part back to the mysql_connect() function. I was thrown off track at first when the code was hung up on a mysql_select_db() function. Turns out that mysql_connect(), if called twice in an execution series with the same parameters, will take the old link and return that! What The French. So, yes, I read the manual and a fourth param (boolean) can be passed into the function to say I want a NEW connection.

mysql_connect()

The fourth param is called new_link, and the excerpt from php.net is as follows:

If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The new_link parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters. In SQL safe mode, this parameter is ignored.

Good to know. Better to remember. Necessary to understand. Fail on my part.

Just a quick time comparison of PHP’s preg_replace vs. str_replace

Here’s a short and succinct comparison of running time to replace multiple characters in a given string. I ran the test 20 times each, so the numbers you will find are average running times:

$start = microtime();
$str = "23ilrj23oirj23iorj o23irj23klfj23lkjr4ocimior 4r ioj234roij234r io34jrio4jrio34r jio4jr o34jr oi4jr io34 r";
$new_string = preg_replace('/[\w2]/',',',$str);
$end = microtime();
echo($end - $start);
echo "\n";
$start = microtime();
$str = "23ilrj23oirj23iorj o23irj23klfj23lkjr4ocimior 4r ioj234roij234r io34jrio4jrio34r jio4jr o34jr oi4jr io34 r";
$new_string = str_replace(array('2',' ',"\t"),',',$str);
$end = microtime();
echo($end - $start);

The results:

regex: 0.000608
tr: 0.00024099999999999