Consider the following code:
<?php
$conn = mysql_connect('localhost', 'username', 'password');
mysql_select_db('database', $conn);
?>
This works as expected, but how does PHP know what database connection to use when calling mysql_select_db() in the following example?
<?php
mysql_connect('localhost', 'username', 'password');
mysql_select_db('database');
?>
The PHP documentation states that "If the link identifier is not specified, the last link opened by mysql_connect() is assumed." (PHP: mysql_select_db())
Where is the last connection stored or retrieved from?
I suppose a link to the last opened connection is kept somewhere in memory, to make things easier (as we generally often use only one connection).
Quickly going through the sources of
ext/mysql:(All line numbers are in
php_mysql.c— the version of the sources is a random snapshot of PHP 5.3.2-dev from a couple of weeks ago ; so, they might have changed a bit)mysql_connectseems to correspond to the C-level function calledphp_mysql_do_connect(line 922)php_mysql_do_connectfunction callsphp_mysql_set_default_link(line 832)php_mysql_get_default_link(line 908)php_mysql_get_default_linkfunction is called bymysql_select_db, when there is no link passed to it (line 992)And
php_mysql_set_default_linkis calling this to store thedefault_link:That
MySGbeing a macro, defined like this (inphp_mysql_structs.h) :Pretty much looks like a global variable to me 😉
If you want, you can take a look at the sources yourself :
ext/mysql/php_mysql.candext/mysql/php_mysql_structs.h.As I said, this has probably been modified a bit since the version in which I checked — which means the line numbers might not match exactly ; but the functions names are easy anough to understand, so you should be able to track down what calls what and where 🙂