0

I have been trying to generate two tables in database on activation hook. But it generates only the first one table on activation hook . What am i doing wrong in my code?

class Datetimepicker_Tables{

function __construct(){
    add_action('init',array($this,'create_tables'));

}

function activate(){
    $this->create_tables();
    flush_rewrite_rules();
}

function create_tables(){
        global $wpdb;

        $date_table_name = $wpdb->prefix . 'booking_dates';
        $time_table_name = $wpdb->prefix . 'booking_timeslots';
        $charset_collate = $wpdb->get_charset_collate();

        $date_table = "CREATE TABLE $date_table_name (
            `id` int(11) NOT NULL AUTO_INCREMENT,
             `year` int(11) NOT NULL,
             `month` int(11) NOT NULL,
             `day` int(11) NOT NULL,
             PRIMARY KEY (`id`)
            ) $charset_collate;";

        $time_table = "CREATE TABLE $time_table_name (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `bid` int(11) NOT NULL,
            `time` int(11) NOT NULL,
            PRIMARY KEY (`id`),
            KEY `bid` (`bid`),
            CONSTRAINT `booking_timeslots_ibfk_1` FOREIGN KEY (`bid`) REFERENCES `booking_dates` (`id`)
            )  $charset_collate;";  

            require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
            dbDelta( $date_table );
            dbDelta( $time_table );
}
}

$tablesclass = new Datetimepicker_Tables();
register_activation_hook(__FILE__,array($tablesclass,'activate'));
  • REFERENCES booking_dates should be REFERENCES $date_table_name. – Sally CJ Mar 6 at 12:23
  • Are you talking about this -> "$date_table_name = $wpdb->prefix . 'booking_dates';" ? – Afzal Khan Mar 6 at 12:27
  • Yes, the table name. – Sally CJ Mar 6 at 12:33
  • I don't think so, i made a variable and passing a name of the table in that variable. – Afzal Khan Mar 6 at 12:39
  • I was saying that you didn't use the proper table name in the CONSTRAINT clause.. – Sally CJ Mar 6 at 13:00
1

You're not using the proper table name in your CONSTRAINT clause:

CONSTRAINT `booking_timeslots_ibfk_1` FOREIGN KEY (`bid`) REFERENCES `booking_dates` (`id`)

That should be:

CONSTRAINT `booking_timeslots_ibfk_1` FOREIGN KEY (`bid`) REFERENCES `$date_table_name` (`id`)

where $date_table_name (as I could see) is the correct table name.

  • 1
    To add to Sally's answer - the reference in the SQL for the table is "booking_dates" which lacks the database prefix defined in the variable $date_table_name, so the table "booking_dates" doesn't actually exist when the query is run. – butlerblog Mar 6 at 13:06
  • You're welcome Afzal. And thank you @butlerblog. :) – Sally CJ Mar 6 at 13:15

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.