Home » Wordpress » How to use wordpress wpdb class to insert data

How to use wordpress wpdb class to insert data

Posted by: admin November 30, 2017 Leave a comment

Questions:

I am new to wordpress I am try to create table and insert data to that table. so within the wordpress database I created table called ‘album’ then I created directory called ‘my-codes'(within root directory/ same level with ‘wp-admin’ , ‘wp-content, ‘wp-includes’ directories)

within that directory I created insert.php then i added following code

<?php       
global $wpdb;
$wpdb->insert($wpdb->album , array("ID"=>1, "Name"=>'something'), array("%d", "%s"));

 ?>

but it give this error Fatal error: Call to a member function insert() on a non-object in C:\wamp\www\wordpress\my-codes\insert.php what is the mistake I did, please help me.

Answers:

You have to load the WordPress files within your script, so that you have access to WordPress’ $wpdb object:

require_once( '../wp-load.php' );

This will load all of WordPress, even the functionality you don’t need. If you want to only load the database part, read this article.


Update – The first argument to the insert method should be the name of your table:

$wpdb->insert(
    'album',
     array("ID"=>1, "Name"=>'something'),
     array("%d", "%s")
);

Questions:
Answers:
require (dirname(dirname(__FILE__)) . '/wp-blog-header.php');
require (ABSPATH . WPINC . '/compat.php');
require (ABSPATH . WPINC . '/functions.php');
require (ABSPATH . WPINC . '/classes.php');

require_wp_db();
global $wpdb; // Look look! Over here! line 270 in wp-settings.php

if ( !empty($wpdb->error) )
        dead_db();

 //Execute your query here

Questions:
Answers:

I would recommend using the WordPress Options API instead of creating a custom table, unless options won’t fit your needs. Also, place all your code in your theme’s functions.php. That way, you won’t need to load any other WordPress files externally. They’re already loaded for you automatically if your code is in functions.php.

Here’s a quick example of how to store data in the database using options ( taken from the WP Codex article linked above ):

// Create an option to the database
add_option( $option, $value = , $deprecated = , $autoload = 'yes' );

// Removes option by name.
delete_option( $option );

// Fetch a saved option
get_option( $option, $default = false );

// Update the value of an option that was already added.
update_option( $option, $newvalue );

Options are much easier to implement and generally less error prone than direct database access. 🙂