2

Is there a built-in way to check to see if a DB table exists via PHP? I'd like to add that to my API call and create the table if necessary.

Thanks!

3

There is a specific CiviCRM function (but all the ways in the other answers will be just as good :-)):

CRM_Core_DAO::checkTableExists($tableName)

This function will return TRUE or FALSE.

2

If you're writing PHP in a CiviCRM extension - you can add a /sql/install.sql file in which you can execute MySQL commands like:

CREATE TABLE IF NOT EXISTS
2

CRM_Queue_BAO_QueueItem:: findCreateTable() contains an example of how CiviCRM does this, and the presence of this suggested that no "canned" method might exist already.

$checkTableSql = "show tables like 'civicrm_queue_item'";
$foundName = CRM_Core_DAO::singleValueQuery($checkTableSql);
if ($foundName == 'civicrm_queue_item') {
  return TRUE;
}

But I was wrong, see ErikH's answer: CRM_Core_DAO::checkTableExists()!

0

If you know the name of the table, you could use MySQL via command line:

Log into MySQL using terminal and then execute a command:

mysql -u [username] -p

mysql> show tables like "test1";

If it exists, you will get an output such as:

+------------------------+
| Tables_in_test (test1) |
+------------------------+
| test1                  |
+------------------------+
1 row in set (0.00 sec)

https://www.electrictoolbox.com/check-if-mysql-table-exists/

1
  • I need to do it from my PHP script. I could probably execute that query using CRM_Core_DAO::executeQuery() – Sleewok Feb 15 '17 at 20:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.