2

I have marked many of developers using

$con1 = mysql_connect('localhost', 'username', 'password');
$rv1 = mysql_select_db('db1'); // not added connection

Instead

$con1 = mysql_connect('localhost', 'username', 'password');
$rv1 = mysql_select_db('db1', $con1); // added connection

Can I know the difference between this both?

Actually this both are giving same result

SagarPPanchal
  • 9,839
  • 6
  • 34
  • 62

3 Answers3

2

The mysql_ functions will implicitly use the last connection which was opened with mysql_connect, if you do not pass an explicit connection parameter. So, yes, in this case it's the same result whether you pass the parameter or not. You will get different results should you happen to open more than one connection using mysql_connect.

Note that implicitly relying on an open connection is bad practice, precisely because your application will screw up if you need to open more connections sometime later. Also note that the mysql_ API is dead, switch to mysqli or PDO.

deceze
  • 510,633
  • 85
  • 743
  • 889
2

Take a look at the PHP manual:

http://www.php.net/manual/en/function.mysql-select-db.php

Without a link identifier, mysql_select_db will use the last connection opened with mysql_connect or it will try to connect without any parameter. So the second one is safer and you could use multiple connections.

mysql_select_db and mysql_connect is deprecated though. You should switch to PDO or mysqli.

Evan
  • 123
  • 1
  • 8
1

Taken from the documentation:

bool mysql_select_db ( string $database_name [, resource $link_identifier = NULL ] )

link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Basically it will used the last known connection object if none is provided. In your case, the last known connection was created on the previous line. This is an optional parameter so the function will operate in the same way if the connection is passed explicitly or not.


On a related note, please notice the big red warning at the top of the documentation page I have linked to. The mysql_* extensions are deprecated and it is recommended that you use a different extension. For a more detailed explanation, please take a look at this thread:

Why shouldn't I use mysql_* functions in PHP?

Community
  • 1
  • 1
Lix
  • 47,311
  • 12
  • 103
  • 131