使用 WordPress 的时候,如果想直接使用WP里封装的数据库操作的类 wp-db.php,只需要将 wp-blog-header.php 引入到当前文件中就可以使用了。
- define('PATH', dirname(dirname(__FILE__)).'/');
- require_once(PATH . '../wp-blog-header.php');
- global $wpdb;
插入数据时,其中一种方法是使用 wp-db 类中的 insert() 函数。
- $table = "test_table";
- $data_array = array(
- 'column_1' => 'data1',
- 'column_2' => 'data2'
- );
- $wpdb->insert($table,$data_array);
第一个参数是数据库表中的名字,第二个参数是要插入的数据,是一个数组。数组中的 key 的名字就是表中的列名。其实 insert() 函数还有第三个参数 format,感兴趣的朋友可以在 wp-db.php 的方法定义里看看更新数据时,可以用 update() 函数,例如下面的方法:
- $table = "test_table";
- $data_array = array(
- 'column_1' => 'new_data1'
- );
- $where_clause = array(
- 'column_2' => 'data2'
- );
- $wpdb->update($table,$data_array,$where_clause);
要从数据库中取数据,也有很多种方法,其中一种如下:
- $querystr = "SELECT column_1 FROM test_table";
- $results = $wpdb->get_results($querystr);
- $i=0;
- while ($i< count($results)){
- echo $results[$i]->column_1."<br />";
- $i++;
- }