Search code examples
mysqljoomlajoomla1.5

Check if a column exists in Joomla table


I've a table with the columns id and name. I want to know if another new column filters exist (of course it doesn't exist).

This is what I'm doing

$db = JFactory::getDBO();
$query = "SHOW COLUMNS FROM `#__facets` LIKE 'filters'";
$db->setQuery($query);
$res = $db->query();

If I print $res it shows resource(675) of type (mysql result) when I was expecting NULL because column doesnt exist.

If I try with name (the column exist):

$db = JFactory::getDBO();
$query = "SHOW COLUMNS FROM `#__facets` LIKE 'name'";
$db->setQuery($query);
$res= $db->query();

It returns also resource(234) of type (mysql result).

How can I control if the column exist? The query is OK because it works on MySQL Workbench

PS: I'm using Joomla 1.5 so I can't use getTableColumns()


Solution

  • The problem was on the $res= $db->query(); line.

    To get the desired NULL I had to loadResult() instead of just query(). So the correct code is:

    $db = JFactory::getDBO();
    $query = "SHOW COLUMNS FROM `#__facets` LIKE 'filters'";
    $db->setQuery($query);
    $res = $db->loadResult();