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:wampwwwwordpressmy-codesinsert.php
what is the mistake I did, please help me.
You have to load the WordPress files within your script, so that you have access to WordPress’
$wpdb
object: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: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 ):
Options are much easier to implement and generally less error prone than direct database access. 🙂