w3resource

PHP mysqli: select_db() function

mysqli_select_db() function/ mysqli::select_db

The mysqli_select_db() function/ mysqli::select_db is used to change the default database for the connection.

Syntax:

Object oriented style

bool mysqli::select_db ( string $dbname )

Procedural style

bool mysqli_select_db ( mysqli $link , string $dbname )

Parameter:

Name Description Required/Optional
link A link identifier returned by mysqli_connect() or mysqli_init() Required for procedural style only and Optional for Object oriented style
dbname The database name. Required

Usage: Procedural style

mysqli_select_db(connection,dbname);

Parameter:

Name Description Required/Optional
connection Specifies the MySQL connection to use Required
dbname Specifies the default database to be used Required

Return value:

Returns TRUE on success or FALSE on failure.

Version: PHP 5, PHP 7

Example of object oriented style:

<?php
$mysqli = new mysqli("localhost", "user1", "datasoft123", "hr");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
    $row = $result->fetch_row();
    printf("Default database is %s.\n", $row[0]);
    $result->close();
}

/* change db to world db */
$mysqli->select_db("hr");

/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
    $row = $result->fetch_row();
    printf("Default database is %s.\n", $row[0]);
    $result->close();
}

$mysqli->close();
?>

Output:

Default database is hr. Default database is hr.

Example of the Procedural style

<?php
$link = mysqli_connect("localhost", "user1", "datasoft123", "hr");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* return name of current default database */
if ($result = mysqli_query($link, "SELECT DATABASE()")) {
    $row = mysqli_fetch_row($result);
    printf("Default database is %s.\n", $row[0]);
    mysqli_free_result($result);
}

/* change db to world db */
mysqli_select_db($link, "hr");

/* return name of current default database */
if ($result = mysqli_query($link, "SELECT DATABASE()")) {
    $row = mysqli_fetch_row($result);
    printf("Default database is %s.\n", $row[0]);
    mysqli_free_result($result);
}

mysqli_close($link);
?>

Output:

Default database is hr.
Default database is hr.

See also

PHP Function Reference

Previous: rollback
Next: set_charset



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/php/function-reference/mysqli_select_db.php