I’m running a script that check if a table exists, if it doesn’t I create it, then either way data is added to it.
First time I run the script (when the table doesn’t exist) the table is created (checked this in PHPmyAdmin) but an error is thrown when adding data.
InvalidArgumentException Invalid table: nc_districts_notts
(Kirby/src/Database/Query.php - 259).
I’m guessing this means the table doesn’t exist as it’s validating the table?
If i run the script again (Now table exists) it runs fine and data is added.
Am I missing something?
Do I need to do something before the adding the data to the table?
Script sections below:
This is all within the page controller.
The table is checked via the Db::select()
method.
// The Page
$county_page = page($region);
// Table Abbreviation
$county_table_abb = $county_page->county_abb()->value();
// The Table
$db_district_table = 'nc_districts_' . $county_table_abb;
//
$district_table_exists = true;
try {
$selectResult = Db::select( $db_district_table );
} catch(Exception $error) {
$district_table_exists = false;
}
Then create the table if it doesn’t exist via the Db::execute()
method:
if ( !$district_table_exists ) {
//
$create_districts_table_query = "CREATE TABLE `$db_district_table` (";
$create_districts_table_query.= "`id` int(11) NOT NULL AUTO_INCREMENT,";
$create_districts_table_query.= "PRIMARY KEY (`id`),";
$create_districts_table_query.= "`district_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,";
$create_districts_table_query.= "`district_slug` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,";
$create_districts_table_query.= "`region_id` int(11) DEFAULT NULL";
$create_districts_table_query.= ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;";
//
$district_table_exists = Db::execute( $create_districts_table_query );
}
Then some logic to get and loop through the data and the Db::insert()
method.
$district_id = Db::insert( $db_district_table, [
'district_name' => $the_district,
'district_slug' => strtolower( str_replace( ' ', '-', trim( $the_district ) ) ),
'region_id' => $region_id
]);