Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

MariaDB selects the database


May 16, 2021 MariaDB


Table of contents


After you connect to MariaDB, you must select the database you want to use because many databases may exist. T here are two ways to do this: from command prompts or through PHP scripts.

Command prompt

When selecting a database at the command prompt, simply use the SQL command'use '

[root@host]# mysql -u root -p

Enter password:******

mysql> use PRODUCTS;

Database changed

mysql> SELECT database();  
+-------------------------+ 
| Database                | 
+-------------------------+ 
| PRODUCTS                | 
+-------------------------+ 

Once the database is selected, all subsequent commands will operate on the selected database.

Note - All names (for example, databases, tables, fields) are case sensitive. M ake sure that the command is in the correct case.

PHP selects the database script

PHP provides a function for database mysql_select_db selection. T he function uses two parameters, one optional, and returns the value "true" when selected successfully, or false on failure.

Grammar

Check out the select database script syntax below.

bool mysql_select_db( db_name, connection );

The description of the parameters is given below -

S.No Parameters and descriptions
1

DB_NAME

This requires the parameter to specify the name of the database to be used.

2

Connection

If not specified, this optional parameter uses the most recently used connection.

Try the following sample code to select a database -

<html>
   <head>
      <title>Select a MariaDB Database</title>
   </head>

   <body>
      <?php
         $dbhost = 'localhost:3036';
         $dbuser = 'guest1';
         $dbpass = 'guest1a';
         $conn = mysql_connect($dbhost, $dbuser, $dbpass);
      
         if(! $conn ) {
            die('Could not connect: ' . mysql_error());
         }
         echo 'Connected successfully';
         
         mysql_select_db( 'PRODUCTS' );
         mysql_close($conn);
      ?>
   </body>
</html>

After a successful selection, you will see the following output -

mysql> Connected successfully