[MySQL Tutorial 4] Selecting Database and Table

3

In the previous PHP tutorial on creating database, you learnt how to create and delete a database in MySQL. In this tutorial, you will learn how to select database and table.

Every database consists of tables that store data. To check the tables of a database, first select that database by the following command:

Use database_name;


Where database_name is the name of any database you want to select. For example;

Use mysql;


This can be done using PHP as follows:
<?php

$link=mysql_connect('localhost','root','your_password');

mysql_select_db('mysql');

echo "connected to mysql";

?>

 

This command selects “mysql” database. The output is shown as follows:

Now, to check which tables this database has, use the following:

Show tables;


This command will display a list of all the tables in “mysql” database. To see the contents of a particular table, you need to use select query which is as follows:

Select * from table_name;


For example,

Select * from user;


This command will display the contents of “user” table.

Suppose we have created a database named “new2” with a table “example2”. And the table contains salary and employee id as two columns.

As described above, we select the table “example2” from “new2” database as follows:

Use new2;

Select * from example2;

 

The output is as follows:

To do this using PHP program, put this command in mysql_query function as follows:

<?php

$link=mysql_connect('localhost','root','your_password');

mysql_select_db('new2');

echo "connected to new2";

$r=mysql_query("select * from example2");

$ro=mysql_fetch_array($r);

echo "<table border='1'>";

echo "<tr><th>sal</th><th>empid</th></tr>";

echo "<tr><td>";

echo $ro['sal'];

echo "</td><td>";

echo $ro['empid'];

echo "</td></tr>";

echo "</table>";

?>

The output will be shown as:

Mysql_fetch_array function is used to to fetch the data from select query, which is then displayed in a tabular format in the browser using html tags. Mysql_select_db function is used for select the particular database.

Now that you know how to select database and table, continue with the next tutorial on how to create a table within a database. Also, if you have any query, please leave a comment below.

Share.

3 Comments

  1. I do have a couple of questions for you if it’s allright. And, if you are posting on additional online sites, I would like to keep up with you. Would you list all of your shared sites like your twitter feed, Facebook page or linkedin profile?

    • Thanks for your comment. Obviously, you can leave the questions for discussion on the post. If you would like to stay updated on the upcoming posts, follow Durofy.com on twitter, facebook and linkedin. Links to these sites are available on the website.

  2. Pingback: [MySQL Tutorial 6] Inserting Values in Table | Durofy

Leave A Reply