How to properly insert data into custom table via plugin

That’s not a good practice trying to connect the DB by your own methods while WP does it for you initially.


The problem with this is that I have to declare these variables
($db_host, $db_user, $db_pass, $db_name) inside the plugin source
code.

All these properties are defined in wp-config.php file, located in the root area.

If you were to get these constants then, just include the file and call the constants, or use REGEX (better use REGEX, because there might be other callbacks that require loading WordPress)

// loading the config file to pull the DB_* constants
$dirname = dirname(__FILE__);
$root = false !== mb_strpos( $dirname, 'wp-content' ) ? mb_substr( $dirname, 0, mb_strpos( $dirname, 'wp-content' ) ) : $dirname;
// if $root is not correct, provide a static path then, $root="/path/to/root/dir"
// assuming constants are ready (wp is configured), let's get them.
require_once( $root . "wp-config.php" );
echo var_dump(
    'DB name', DB_NAME,
    'DB user', DB_USER,
    'DB password', DB_PASSWORD,
    'DB host', DB_HOST
);

Here’s a better solution:

Load WordPress

require( '/wp-blog-header.php' ); You should provide a working path to that file!

To test if you have loaded WordPress successfully, dump out something:

add_action("wp", function() { 
    echo sprintf( "Yes! I am creating with WordPress v. %s!\n", get_bloginfo("version") );
    exit("I exits\n");
});

Now use WordPress DB API

To insert data, there’s this wpdb::insert you should use. Here the syntax

$wpdb->insert( $table, $data, $format ); and example use:

$wpdb->insert( 
    'messages', 
    array( 
        'PM_ID'     => (int) $pm_id,
        'sender'    => $current_user->ID,
        'recipient' => (int) $recipient,
        'message'   => "Hello!\n",
        'date'      => time()
    )
);
$record_id = $wpdb->insert_id;

In the example, the array in $wpdb->insert‘s 2nd param is an array with indexes as columns names, and values to be inserted for these cols in an independent record that you can get its ID with $wpdb->insert_id which gets last record insert ID in that table.

Hope that helps, if at least you stay away from SQL injection using $wpdb::insert or prepared statements instead of direct queries.

Leave a Comment