How to Display Certain Fields of a Table in MySQL Using PHP



PHP


In this article, we show how to display certain fields of a table in MySQL using PHP.

Say, for example, a table has many different fields, for example, a user's first name, last name, email address, address, city, state, zip code, telephone number. However, all we want to show is the user's first name, last name, and email address, and not display any of the other columns.

Using PHP, we can selectively decide which columns of a table we want to display.

An example is below:

In the below table, we show the images column, containing the image of the chips, the Type column containing the type of chips it is, and the Price column containing the price of the chips.

Banana
$0.79
Mango
$1.99
Cantaloupe
$3.99
Honeydew
$4.99


Now let's say we wanted to take out the images column and only display the Type and Price columns.

We can do this and the table would now look like:

$0.79
$1.99
$3.99
$4.99


Now we only display the images and Price columns.

Coding

To display a certain field or certain fields of a table in MySQL using PHP, first you connect to the MySQL server and database containing the table you want to display.

After, you select the specific field(s) that you want displayed using the

mysql_query function to select the specific field that you want displayed from your table.

The full code is below:



The first block of code is where you place in your server name, user name, password, database name, and table name of the MySQL server, database, and table, that you want to connect to.

The second block of code connects you to the MySQL server and the database of in the MySQL server that you want to connect to.

The third block of code chooses the specific field(s) of the table in the database that you want selected. This is represented in the above code as field_name1 and field_name2. For example, if we are dealing with a table containing customer information and we just to show the display the columns containing the customer's name and email, the columns for field_name1 and field_name2 might be name and email, if this is what the columns which we created in MySQL are named.

The fourth block of code prints outs that field of the table. To learn more about using PHP to display tables, see How to Display a MySQL Table of a Database Using PHP.


Related Resources

How to Sort a Field of a MySQL Table in Ascending Order in PHP

How to Select Specific Columns from a MySQL Table Using PHP

How to Select a Specific Row of a MySQL Table Using PHP

How to Find the Number of Rows in a MySQL Table Using PHP




HTML Comment Box is loading comments...