subramanian
subramanian

Reputation: 53

How to check column exist or not before select that column from table

Below is the query I used to select multiple columns from one of my tables. I get the column names from user to select from the table. If the user gives a wrong column name it shows Unknown column error. How can I check if that column exists in the table before going to select?

SELECT `address_id`,`address_firstname`,` afserfw` 
FROM `patsm_addresstable` 
WHERE `address_id`='28'
LIMIT 0, 25 

This would give the following error:

#1054 - Unknown column ' afserfw' in 'field list' 

Upvotes: 0

Views: 781

Answers (1)

O. Jones
O. Jones

Reputation: 108839

This query will give you a list of columns in a particular table with their datatypes.

SELECT COLUMN_NAME, DATA_TYPE
  FROM INFORMATION_SCHEMA.COLUMNS
 WHERE TABLE_SCHEMA = DATABASE()
   AND TABLE_NAME = 'tablename'

You can, when constructing a query against any table, use this resultset to determine whether a given column exists.

But be careful: a web application allowing end-users to give you column names is hard to make secure against intrusion by cybercrooks.

Upvotes: 1

Related Questions