3

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.

4

3 回答 3

1

您必须在脚本中加载 Wordpress 文件,以便您可以访问 Wordpress 的$wpdb对象:

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

这将加载所有 Wordpress,甚至是您不需要的功能。如果您只想加载数据库部分,请阅读本文


更新- 该insert方法的第一个参数应该是您的表的名称:

$wpdb->insert(
    'album',
     array("ID"=>1, "Name"=>'something'),
     array("%d", "%s")
);
于 2012-11-16T02:32:25.220 回答
0
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
于 2012-11-16T02:35:35.783 回答
0

我建议使用WordPress 选项 API而不是创建自定义表,除非选项不符合您的需要。此外,将所有代码放在主题的functions.php. 这样,您就不需要从外部加载任何其他 WordPress 文件。如果您的代码在functions.php 中,它们已经为您自动加载。

这是一个如何使用选项将数据存储在数据库中的快速示例(取自上面链接的 WP Codex 文章):

// 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 );

与直接访问数据库相比,选项更容易实现并且通常更不容易出错。:)

于 2012-11-16T02:41:50.720 回答