Главная | Руководство по MySQL | MySQL Manual | Документация к HTTP серверу Apache | Apache HTTP Server Documentation | downloads | faq

искать  Язык: Английский


(PHP 4, PHP 5)

mysql_select_dbВыбирает базу данных MySQL


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

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

mysql_select_db() выбирает для работы указанную базу данных на сервере, на который ссылается переданный указатель. Если параметр указателя опущен, используется последнее открытое соединение. Если нет ни одного открытого соединения, функция попытается соединиться с сервером аналогично функции mysql_connect(), вызванной без параметров.

Каждый последующий вызов функции mysql_query() будет работать с выбранной базой данных.

Пример #1 Пример использования mysql_select_db()


       or die (
'Not connected : ' mysql_error());

// сделать foo текущей базой данных
mysql_select_db('foo'$lnk) or die ('Can\'t use foo : ' mysql_error());


См. также mysql_connect(), mysql_pconnect() и mysql_query().

Для совместимости, как алиас, доступна устаревшая функцмия mysql_selectdb(). Однако, использовать её крайне не рекомендуется.

User Contributed Notes
riad93 at mail dot ru
12-Sep-2009 11:44
You can use DataBases without <?php mysql_select_db() ?>

And you will havenot james at gogo dot co dot nz's problems :)

mysql_query('SELECT * FROM database_name.table_name');

anotheruser at example dot com
12-Aug-2008 11:57
Cross-database join queries, expanding on Dan Ross's post...

Really, this is a mysql specific feature, but worth noting here.  So long as the mysql user has been given the right permissions to all databases and tables where data is pulled from or pushed to, this will work.  Though the mysql_select_db function selects one database, the mysql statement may reference another (the syntax for referencing a field in another db table being 'database.table.field').


    FROM tblPosts
    LEFT JOIN Users.tblUsers ON AuthorID = Users.tblUsers.UserID
    GROUP BY PostID,AuthorID,Username

$dblink = mysql_connect("somehost", "someuser", "password");
$qry = mysql_query($sql_statement,$dblink);

me at khurshid dot com
09-Sep-2007 06:03
Problem with connecting to multiple databases within the same server is that every time you do:
mysql_connect(host, username, passwd);
it will reuse 'Resource id' for every connection, which means you will end with only one connection reference to avoid that do:
mysql_connect(host, username, passwd, true);
keeps all connections separate.
19-Aug-2005 12:09
About opening connections if the same parameters to mysql_connect() are used: this can be avoided by using the 'new_link' parameter to that function.

This parameter has been available since PHP 4.2.0 and allows you to open a new link even if the call uses the same parameters.
buzz at oska dot com
06-May-2005 12:39
Opening multiple connection handles with:


causes the connection ID/handle to be REUSED if the exact same parameters are passed in to it.   This can be annoying if you want to work with multiple databases on the same server, but don't want to (a) use the database.table syntax in all your queries or (b) call the mysql_select_db($database) before every SQL query just to be sure which database you are working with.    
My solution is to create a handle for each database with mysql_connect (using ever so slightly different connection properties), and assign each of them to their own database permanently.  each time I do a mysql_query(...) call, I just include the connection handle that I want to do this call on eg (ive left out all error checking for simplicity sake):

// none of thesehandles are re-used as the connection parameters are different on them all, despite connecting to the same server (assuming 'myuser' and 'otheruser' have the same privileges/accesses in mysql)
$handle_db1 = mysql_connect("localhost","myuser","apasswd");
$handle_db2 = mysql_connect("","myuser","apasswd");
$handle_db3 = mysql_connect("localhost:3306","myuser","apasswd");
$handle_db4 = mysql_connect("localhost","otheruser","apasswd");

// give each handle it's own database to work with, permanently.

//do a query from db1:
$query = "select * from test"; $which = $handle_db1;

//do a query from db2 :
$query = "select * from test"; $which = $handle_db2;


Note that we didn't do a mysql_select_db between queries , and we didn't use the database name in the query either.

Of course, it has the overhead of setting up an extra connection.... but you may find this is preferable in some cases...
james at gogo dot co dot nz
17-Jan-2004 12:45
Be carefull if you are using two databases on the same server at the same time.  By default mysql_connect returns the same connection ID for multiple calls with the same server parameters, which means if you do

= mysql_connect(...stuff...);
$db2 = mysql_connect(...stuff...);
mysql_select_db('db1', $db1);
mysql_select_db('db2', $db2);

then $db1 will actually have selected the database 'db2', because the second call to mysql_connect just returned the already opened connection ID !

You have two options here, eiher you have to call mysql_select_db before each query you do, or if you're using php4.2+ there is a parameter to mysql_connect to force the creation of a new link.
doug at xamo dot com
17-Dec-2003 08:39
When you need to query data from multiple databases, note that mysql_select_db("db2")  doesn't prevent you from fetching more rows with result sets returned from "db1".


$res_db1=mysql_query("select * from foobar");



$res_db2=mysql_query("select * from test where id='$row_db1->id'");

credits | contact