L
L
Leingard2018-02-16 10:54:57
MySQL
Leingard, 2018-02-16 10:54:57

How to check for the existence of a table column?

Good afternoon!
I am writing a module for cms, the bottom line is that I need to add the htmlcolor column to the product table in sql at the first installation. It is important that when reinstalling the module, it does not erase this column.
I'm doing a PHP check, example:
$a = $this->db->query("SELECT htmlcolor FROM product");
if (!empty($a)) {
$this->db->query("ALTER TABLE product ADD `htmlcolor` VARCHAR( 6 ) NOT NULL");
}
Is everything correct? Or is there a better way?
Thanks :)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nick Sdk, 2018-02-16
@lidacriss

maybe like this

SELECT count(COLUMN_NAME) 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_SCHEMA = 'database_name' AND TABLE_NAME = 'table_name' AND COLUMN_NAME='need_column';

in response will return
1 - if there is such a field
0 - if there is no such field

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question