How to include $wpdb in wordpress plugin?

后端 未结 1 1624
北恋
北恋 2020-12-31 19:36

I\'ve been developing for some time on a plugin in wordpress, but one problem keeps bugging me. I want to export a database-table as an excel file

相关标签:
1条回答
  • 2020-12-31 20:34

    If you're creating a WordPress plugin, you don't need to include those files manually.

    If you want to export your table, why don't you create a function/class for it and pass the $wpdb to it (if you need it). You can also use the normal MySQLi-class (from PHP) do access your MySQL Database.


    If you simply want to access the MySQL Database with the stored login-values which are used by WordPress, you can include the wp_config-file from the WordPress root-directory. It has some (self explaining) global fields which you could use to connect to your database:

    include "WP-ROOT-PATH/wp-config.php";
    $db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
    // Test the connection:
    if (mysqli_connect_errno()){
        // Connection Error
        exit("Couldn't connect to the database: ".mysqli_connect_error());
    }
    

    After that you have a instance of the MySQLi-class (as mentioned above) which you can use to access your Database.

    I'm however not sure if this is the perfect way to go but it sure works.


    To Debug WordPress (if something doesn't work and there is no Error-Message) you should activate debugging in the wp-config.php-file:

    /**
     * For developers: WordPress debugging mode.
     *
     * Change this to true to enable the display of notices during development.
     * It is strongly recommended that plugin and theme developers use WP_DEBUG
     * in their development environments.
     */
    define('WP_DEBUG', true);
    

    Also, if you're testing your PHP-Scripts on a local server, you should turn the display_error to on in your php.ini-file:

    ; This directive controls whether or not and where PHP will output errors,
    ; notices and warnings too. Error output is very useful during development, but
    ; it could be very dangerous in production environments.
    display_errors = On
    

    However this should only be done on your local test-server, not in a productive scenario.

    0 讨论(0)
提交回复
热议问题