Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use wordpress wpdb class to insert data

Tags:

php

wordpress

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.

like image 291
user1784592 Avatar asked Jun 27 '26 18:06

user1784592


1 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")
);
like image 130
Joseph Silber Avatar answered Jun 30 '26 07:06

Joseph Silber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!