- mysql_select_db
- Описание
- Список параметров
- Возвращаемые значения
- Примеры
- Примечания
- Смотрите также
- mysql_select_db
- Описание
- Список параметров
- Возвращаемые значения
- Примеры
- Примечания
- Смотрите также
- User Contributed Notes 6 notes
- mysqli_select_db
- Parameters
- Return Values
- Errors/Exceptions
- Examples
- mssql_select_db
- Список параметров
- Возвращаемые значения
- Примеры
- Смотрите также
- Selecting MySQL Database
- Selecting MySQL Database from the Command Prompt
- Example
- Selecting a MySQL Database Using PHP Script
- Syntax
- Example
- Output
mysql_select_db
Данное расширение устарело, начиная с версии PHP 5.5.0, и будет удалено в будущем. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API и соответствующий FAQ для получения более подробной информации. Альтернативы для данной функции:
Описание
Выбирает для работы указанную базу данных на сервере, на который ссылается переданный дескриптор соединения. Каждый последующий вызов функции mysql_query() будет работать с выбранной базой данных.
Список параметров
Имя выбираемой базы данных.
Соединение MySQL. Если идентификатор соединения не был указан, используется последнее соединение, открытое mysql_connect() . Если такое соединение не было найдено, функция попытается создать таковое, как если бы mysql_connect() была вызвана без параметров. Если соединение не было найдено и не смогло быть создано, генерируется ошибка уровня E_WARNING .
Возвращаемые значения
Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.
Примеры
Пример #1 Пример использования mysql_select_db()
$link = mysql_connect ( ‘localhost’ , ‘mysql_user’ , ‘mysql_password’ );
if (! $link ) die( ‘Не удалось соединиться : ‘ . mysql_error ());
>
// выбираем foo в качестве текущей базы данных
$db_selected = mysql_select_db ( ‘foo’ , $link );
if (! $db_selected ) die ( ‘Не удалось выбрать базу foo: ‘ . mysql_error ());
>
?>
Примечания
Замечание:
Для обратной совместимости может быть использован следующий устаревший псевдоним: mysql_selectdb()
Смотрите также
- mysql_connect() — Открывает соединение с сервером MySQL
- mysql_pconnect() — Устанавливает постоянное соединение с сервером MySQL
- mysql_query() — Посылает запрос MySQL
mysql_select_db
Данный модуль устарел, начиная с версии PHP 5.5.0, и удалён в PHP 7.0.0. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API. Альтернативы для данной функции:
Описание
Выбирает для работы указанную базу данных на сервере, на который ссылается переданный дескриптор соединения. Каждый последующий вызов функции mysql_query() будет работать с выбранной базой данных.
Список параметров
Имя выбираемой базы данных.
Соединение MySQL. Если идентификатор соединения не был указан, используется последнее соединение, открытое mysql_connect() . Если такое соединение не было найдено, функция попытается создать таковое, как если бы mysql_connect() была вызвана без параметров. Если соединение не было найдено и не смогло быть создано, генерируется ошибка уровня E_WARNING .
Возвращаемые значения
Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.
Примеры
Пример #1 Пример использования mysql_select_db()
$link = mysql_connect ( ‘localhost’ , ‘mysql_user’ , ‘mysql_password’ );
if (! $link ) die( ‘Не удалось соединиться : ‘ . mysql_error ());
>
// выбираем foo в качестве текущей базы данных
$db_selected = mysql_select_db ( ‘foo’ , $link );
if (! $db_selected ) die ( ‘Не удалось выбрать базу foo: ‘ . mysql_error ());
>
?>
Примечания
Замечание:
Для обратной совместимости может быть использован следующий устаревший псевдоним: mysql_selectdb()
Смотрите также
- mysql_connect() — Открывает соединение с сервером MySQL
- mysql_pconnect() — Устанавливает постоянное соединение с сервером MySQL
- mysql_query() — Посылает запрос MySQL
User Contributed Notes 6 notes
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
$db1 = 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.
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.
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’).
$sql_statement = «SELECT
PostID,
AuthorID,
Users.tblUsers.Username
FROM tblPosts
LEFT JOIN Users.tblUsers ON AuthorID = Users.tblUsers.UserID
GROUP BY PostID,AuthorID,Username
» ;
$dblink = mysql_connect ( «somehost» , «someuser» , «password» );
mysql_select_db ( «BlogPosts» , $dblink );
$qry = mysql_query ( $sql_statement , $dblink );
Note that the manual is slightly misleading it states :-
«Sets the current active database on the server that’s associated with the specified link identifier. Every subsequent call to mysql_query() will be made on the active database.»
The 2nd statement is not true or at best unclear.
mysql_query() manual entry actually correctly states it will use the last link opened by mysql_connect() by default.
Thus if you have 2 connections you will need to specify the connection when calling mysql_query or issue the connect again to ensure the 1st database becomes the default, simply using mysql_select_db will not make the 1st database the default for subsequent calls to mysql_query.
Its probably only apparent when the two databases are on different servers.
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.
- MySQL
- mysql_affected_rows
- mysql_client_encoding
- mysql_close
- mysql_connect
- mysql_create_db
- mysql_data_seek
- mysql_db_name
- mysql_db_query
- mysql_drop_db
- mysql_errno
- mysql_error
- mysql_escape_string
- mysql_fetch_array
- mysql_fetch_assoc
- mysql_fetch_field
- mysql_fetch_lengths
- mysql_fetch_object
- mysql_fetch_row
- mysql_field_flags
- mysql_field_len
- mysql_field_name
- mysql_field_seek
- mysql_field_table
- mysql_field_type
- mysql_free_result
- mysql_get_client_info
- mysql_get_host_info
- mysql_get_proto_info
- mysql_get_server_info
- mysql_info
- mysql_insert_id
- mysql_list_dbs
- mysql_list_fields
- mysql_list_processes
- mysql_list_tables
- mysql_num_fields
- mysql_num_rows
- mysql_pconnect
- mysql_ping
- mysql_query
- mysql_real_escape_string
- mysql_result
- mysql_select_db
- mysql_set_charset
- mysql_stat
- mysql_tablename
- mysql_thread_id
- mysql_unbuffered_query
mysqli_select_db
Selects the default database to be used when performing queries against the database connection.
Note:
This function should only be used to change the default database for the connection. You can select the default database with 4th parameter in mysqli_connect() .
Parameters
Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()
Return Values
Returns true on success or false on failure.
Errors/Exceptions
If mysqli error reporting is enabled ( MYSQLI_REPORT_ERROR ) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT , a mysqli_sql_exception is thrown instead.
Examples
Example #1 mysqli::select_db() example
mysqli_report ( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
$mysqli = new mysqli ( «localhost» , «my_user» , «my_password» , «test» );/* get the name of the current default database */
$result = $mysqli -> query ( «SELECT DATABASE()» );
$row = $result -> fetch_row ();
printf ( «Default database is %s.\n» , $row [ 0 ]);/* change default database to «world» */
$mysqli -> select_db ( «world» );/* get the name of the current default database */
$result = $mysqli -> query ( «SELECT DATABASE()» );
$row = $result -> fetch_row ();
printf ( «Default database is %s.\n» , $row [ 0 ]);mysqli_report ( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
$link = mysqli_connect ( «localhost» , «my_user» , «my_password» , «test» );/* get the name of the current default database */
$result = mysqli_query ( $link , «SELECT DATABASE()» );
$row = mysqli_fetch_row ( $result );
printf ( «Default database is %s.\n» , $row [ 0 ]);/* change default database to «world» */
mysqli_select_db ( $link , «world» );/* get the name of the current default database */
$result = mysqli_query ( $link , «SELECT DATABASE()» );
$row = mysqli_fetch_row ( $result );
printf ( «Default database is %s.\n» , $row [ 0 ]);The above examples will output:
Default database is test. Default database is world.
mssql_select_db
mssql_select_db() sets the current active database on the server that’s associated with the specified link identifier.
Every subsequent call to mssql_query() will be made on the active database.
Список параметров
To escape the name of a database that contains spaces, hyphens («-«), or any other exceptional characters, the database name must be enclosed in brackets, as is shown in the example, below. This technique must also be applied when selecting a database name that is also a reserved word (such as primary).
A MS SQL link identifier, returned by mssql_connect() or mssql_pconnect() .
If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if mssql_connect() was called, and use it.
Возвращаемые значения
Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.
Примеры
Пример #1 mssql_select_db() example
// Create a link to MSSQL
$link = mssql_connect ( ‘KALLESPC\SQLEXPRESS’ , ‘sa’ , ‘phpfi’ );?php
// Select the database ‘php’
mssql_select_db ( ‘php’ , $link );
?>Пример #2 Escaping the database name with square brackets
// Create a link to MSSQL
$link = mssql_connect ( ‘KALLESPC\SQLEXPRESS’ , ‘sa’ , ‘phpfi’ );?php
// Select the database ‘my.database-name’
mssql_select_db ( ‘[my.database-name]’ , $link );
?>Смотрите также
- mssql_connect() — Open MS SQL server connection
- mssql_pconnect() — Open persistent MS SQL connection
- mssql_query() — Send MS SQL query
Selecting MySQL Database
Once you get connected with the MySQL server, it is required to select a database to work with. This is because there might be more than one database available with the MySQL Server.
Selecting MySQL Database from the Command Prompt
It is very simple to select a database from the mysql> prompt. You can use the SQL command use to select a database.
Example
Here is an example to select a database called TUTORIALS −
[root@host]# mysql -u root -p Enter password:****** mysql> use TUTORIALS; Database changed mysql>
Now, you have selected the TUTORIALS database and all the subsequent operations will be performed on the TUTORIALS database.
NOTE − All the database names, table names, table fields name are case sensitive. So you would have to use the proper names while giving any SQL command.
Selecting a MySQL Database Using PHP Script
PHP uses mysqli_select_db function to select the database on which queries are to be performed. This function takes two parameters and returns TRUE on success or FALSE on failure.
Syntax
mysqli_select_db ( mysqli $link , string $dbname ) : bool
Required — A link identifier returned by mysqli_connect() or mysqli_init().
Required — Name of the database to be connected.
Example
Try the following example to select a database −
Copy and paste the following example as mysql_example.php −
echo 'Connected successfully
'; $retval = mysqli_select_db( $conn, 'TUTORIALS' ); if(! $retval ) < die('Could not select database: ' . mysqli_error($conn)); >echo "Database TUTORIALS selected successfully\n"; mysqli_close($conn); ?>Output
Access the mysql_example.php deployed on apache web server and verify the output.
Database TUTORIALS selected successfully