Select database in php code

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

    Источник

    PHP MySQL Select Data

    The SELECT statement is used to select data from one or more tables:

    or we can use the * character to select ALL columns from a table:

    To learn more about SQL, please visit our SQL tutorial.

    Select Data With MySQLi

    The following example selects the id, firstname and lastname columns from the MyGuests table and displays it on the page:

    Example (MySQLi Object-oriented)

    $servername = «localhost»;
    $username = «username»;
    $password = «password»;
    $dbname = «myDB»;

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) die(«Connection failed: » . $conn->connect_error);
    >

    $sql = «SELECT id, firstname, lastname FROM MyGuests»;
    $result = $conn->query($sql);

    if ($result->num_rows > 0) // output data of each row
    while($row = $result->fetch_assoc()) echo «id: » . $row[«id»]. » — Name: » . $row[«firstname»]. » » . $row[«lastname»]. «
    «;
    >
    > else echo «0 results»;
    >
    $conn->close();
    ?>

    Code lines to explain from the example above:

    First, we set up an SQL query that selects the id, firstname and lastname columns from the MyGuests table. The next line of code runs the query and puts the resulting data into a variable called $result.

    Then, the function num_rows() checks if there are more than zero rows returned.

    If there are more than zero rows returned, the function fetch_assoc() puts all the results into an associative array that we can loop through. The while() loop loops through the result set and outputs the data from the id, firstname and lastname columns.

    The following example shows the same as the example above, in the MySQLi procedural way:

    Example (MySQLi Procedural)

    $servername = «localhost»;
    $username = «username»;
    $password = «password»;
    $dbname = «myDB»;

    // Create connection
    $conn = mysqli_connect($servername, $username, $password, $dbname);
    // Check connection
    if (!$conn) die(«Connection failed: » . mysqli_connect_error());
    >

    $sql = «SELECT id, firstname, lastname FROM MyGuests»;
    $result = mysqli_query($conn, $sql);

    if (mysqli_num_rows($result) > 0) // output data of each row
    while($row = mysqli_fetch_assoc($result)) echo «id: » . $row[«id»]. » — Name: » . $row[«firstname»]. » » . $row[«lastname»]. «
    «;
    >
    > else echo «0 results»;
    >

    You can also put the result in an HTML table:

    Example (MySQLi Object-oriented)

    $servername = «localhost»;
    $username = «username»;
    $password = «password»;
    $dbname = «myDB»;

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) die(«Connection failed: » . $conn->connect_error);
    >

    $sql = «SELECT id, firstname, lastname FROM MyGuests»;
    $result = $conn->query($sql);

    if ($result->num_rows > 0) echo «

    «;
    // output data of each row
    while($row = $result->fetch_assoc()) echo «

    «;
    >
    echo «

    ID Name
    «.$row[«id»].» «.$row[«firstname»].» «.$row[«lastname»].»

    «;
    > else echo «0 results»;
    >
    $conn->close();
    ?>

    Select Data With PDO (+ Prepared Statements)

    The following example uses prepared statements.

    It selects the id, firstname and lastname columns from the MyGuests table and displays it in an HTML table:

    Example (PDO)

    class TableRows extends RecursiveIteratorIterator <
    function __construct($it) <
    parent::__construct($it, self::LEAVES_ONLY);
    >

    function current() return «

    » . parent::current(). «

    «;
    >

    $servername = «localhost»;
    $username = «username»;
    $password = «password»;
    $dbname = «myDBPDO»;

    try $conn = new PDO(«mysql:host=$servername;dbname=$dbname», $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare(«SELECT id, firstname, lastname FROM MyGuests»);
    $stmt->execute();

    Источник

    Читайте также:  Css textarea вертикальное выравнивание
Оцените статью