Welcome to the Question2Answer Q&A. There's also a demo if you just want to try it out.
+1 vote
589 views
in Plugins by
edited by

I am still trying to find out how to create a database table when initializing the plugin (see New Plugin: Best users per month).

I could find the documentation, however, without code example. And checking all existing plugins, I could only find the event logger that uses init_queries.


Now I have 2 questions:


1. Registering the module
In qa-plugin.php: Do I have to register a new php-file? Which type do I need, event?
qa_register_plugin_module('event','qa-event-logger.php', 'qa_event_logger', 'Event Logger'); // (example from event logger)

or can I use init_queries directly in the layer.php?

 

2. Using init_queries
For the code within init_queries (the table name is qa_userscores), I would use the following. Is there any mistake in the code?

function init_queries($tableslc) {
    $tablename=qa_db_add_table_prefix('userscores');
    
    if(!in_array($tablename, $tableslc)) {
        //require_once QA_INCLUDE_DIR.'qa-app-users.php';
        //require_once QA_INCLUDE_DIR.'qa-db-maxima.php';

        return 'CREATE TABLE IF NOT EXISTS `'.
$tablename.'` (
          `date` date NOT NULL,
          `userid` int(10) unsigned NOT NULL,
          `points` int(11) NOT NULL DEFAULT '0',
          KEY `userid` (`userid`),
          KEY `date` (`date`)
        )
        ';
    }
}

 

 

Q2A version: 1.5.1

1 Answer

+1 vote
by
selected by
 
Best answer

You can put init_queries() in any module that is registered by your plugin, but not a layer (since layers are not a type of module).

Your code generally looks OK, except you shouldn't hard code the table name qa_userscores in your SQL, but rather use $tablename that you already et.

by
good to know, thanks a lot!
by
One other thing you may want to do is set an option once the plugin is installed. See this question for more: http://www.question2answer.org/qa/14797/how-handle-non-existing-tables-before-init_queries-was-run

Here's how I do it in my widget plugin: https://github.com/svivian/q2a-widget-anywhere/blob/master/qa-widget-anywhere.php
by
I read your question/post when I tried to figure out how init_queries is used, but I couldn't understand the sense behind.

init_queries is only called (as Gideon said) if admin goes to >plugins. So why should I set another option? For the admin settings: The best-users-plugin has no settings in the admin interface yet...
by
The option is set so that on the front end, you know whether you can select from the table. So in my example on each page it will run the SQL "select * from qa_widgetanyw". If the table does not exist yet it obviously causes errors.
...