Current Location: Home> Function Categories> mysqli::select_db

mysqli::select_db

(mysqli_select_db) Select the default database for database query
Name:mysqli::select_db
Category:MySQLi
Programming Language:php
One-line Description:Select the default database for database query.

Definition and usage

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

Example

Example 1 - Object-Oriented Style

Change the default database for connections:

 <?php
$mysqli = new mysqli ( "localhost" , "my_user" , "my_password" , "my_db" ) ;

if ( $mysqli -> connect_errno ) {
  echo "Failed to connect to MySQL: " . $mysqli -> connect_error ;
  exit ( ) ;
}

// Return the name of the current default database
if ( $result = $mysqli -> query ( "SELECT DATABASE()" ) ) {
  $row = $result -> fetch_row ( ) ;
  echo "Default database is " . $row [ 0 ] ;
  $result -> close ( ) ;
}

// Change the database to "test" database
$mysqli -> select_db ( "test" ) ;

// Return the name of the current default database
if ( $result = $mysqli -> query ( "SELECT DATABASE()" ) ) {
  $row = $result -> fetch_row ( ) ;
  echo "Default database is " . $row [ 0 ] ;
  $result -> close ( ) ;
}

$mysqli -> close ( ) ;
?>

Example 2 - Procedural Style

Change the default database for connections:

 <?php
$con = mysqli_connect ( "localhost" , "my_user" , "my_password" , "my_db" ) ;

if ( mysqli_connect_errno ( ) ) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error ( ) ;
  exit ;
}

// Return the name of the current default database
if ( $result = mysqli_query ( $con , "SELECT DATABASE()" ) ) {
  $row = mysqli_fetch_row ( $result ) ;
  echo "Default database is " . $row [ 0 ] ;
  mysqli_free_result ( $result ) ;
}

// Change the database to "test" database
mysqli_select_db ( $con , "test" ) ;

// Return the name of the current default database
if ( $result = mysqli_query ( $con , "SELECT DATABASE()" ) ) {
  $row = mysqli_fetch_row ( $result ) ;
  echo "Default database is " . $row [ 0 ] ;
  mysqli_free_result ( $result ) ;
}

// Close the connection
mysqli_close ( $con ) ;
?>
Similar Functions
Popular Articles