How to Select Specific Columns from a MySQL Table Using PHP


In this tutorial, we will show how you can select individual columns of a MySQL table using PHP.

A table may be composed of many columns. However, when displaying the table, we can selectively choose which columns we want shown. We do not have to display all the columns of a table. PHP has a SELECT function which allows us to choose exactly which columns we want shown.

We will show now how to use this SELECT function to display the columns you want shown, which may be all the columns or just certain specific ones.

How to Select All of the Columns of a MySQL Table Using PHP

Below we will give you a table, which shows all of the columns which make up a MySQL table.



Below is the complete code to create the table above:

In this above code, the line of code which selects the column to be shown is the 3rd block of code, which has the comments "ATTENTION." This is the block of code which selects all of the columns.

To Select all columns, below is the line of code to do so, which is taken out of the full code above:

When you use the SELECT * statement, this means to select all of the columns that composes a table. The full line SELECT * FROM $table means to select all of the columns of the $table table. Note, though that when you all show all columns of a table, this does not include the Primary Key. MySQL uses this only as an index and does not display it.

How To Select Certain Columns of a MySQL Table Using PHP

Let's say now we don't want to display all of the columns of a table. We only want to select certain columns to show.

We'll again use the above table as an illustration. Let's say we feel confident that our users can identify the chips just by the picture and we feel they don't need the middle column which shows the name of the chips. We can omit the names of the bags of chips and just show the image column of the chips and the price column of the chips.

So now the table will only show this:


Note: You must manually take out the column you're not showing anymore in the last block of PHP Code for that column to be completely deleted.

We will not show the full-length of code again, but that block of code specifically which selects the columns we want chosen. The columns above are named the images column and the Price column.

To show it, we use the lines:

To select the specific columns we want shown, the general format is:

where column1, column2, column3 are the columns you want selected.

In the same way, if you want, you can just show one column. It's very flexible with the SELECT method which PHP provides.

HTML Comment Box is loading comments...