WordPress包含一个操作数据库的类——wpdb wordpress


你有一个自定义的表叫做mytable,那么可以使用如下语句来查询: 

$myrows = $wpdb->get_results( "SELECT id, name FROM mytable" );


1.在数据库上运行任务查询

这个查询函数允许你在wordpress的数据库里运行任何SQL查询。当然了,最好能利用如下的特定函数,

 <?php $wpdb->query('query'); ?> 


1.1 删除属于id为13的文章的‘gargle’meta 键和值。

$wpdb->query("

DELETE FROM $wpdb->postmeta WHERE post_id = '13'

AND meta_key = 'gargle'");


1.2 设置页面 Page 15 的父级页面为 7.

$wpdb->query("

UPDATE $wpdb->posts SET post_parent = 7

WHERE ID = 15 AND post_status = 'static'");


2.选择一个变量

<?php $wpdb->get_var('query',column_offset,row_offset); ?> 


2.1 获取并显示用户数量

<?php

$user_count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $wpdb->users;"));

echo '<p>User count is ' . $user_count . '</p>';

?>

 

2.2 获取并显示 自定义字段值 的总和.

<?php

$meta_key = 'miles';//set this to appropriate custom field meta key

$allmiles=$wpdb->get_var($wpdb->prepare("SELECT sum(meta_value) FROM $wpdb->postmeta WHERE meta_key = %s", $meta_key));

echo '<p>Total miles is '.$allmiles . '</p>';

?> 


3.选择一行

<?php $wpdb->get_row('query', output_type, row_offset); ?> 


3.0 获取ID为10的链接的全部信息

$mylink = $wpdb->get_row("SELECT * FROM $wpdb->links WHERE link_id = 10");

$mylink对象的属性是SQL查询结果的列名(此例中是所有 $wpdb->links表中的列名)。

echo $mylink->link_id; // prints "10"

作为对比, 使用

$mylink = $wpdb->get_row("SELECT * FROM $wpdb->links WHERE link_id = 10", ARRAY_A);

将返回关联数组:

echo $mylink['link_id']; // prints "10"

然后

$mylink = $wpdb->get_row("SELECT * FROM $wpdb->links WHERE link_id = 10", ARRAY_N);

将返回索引数组:

echo $mylink[1]; // prints "10"


4.选择一列

<?php $wpdb->get_col('query',column_offset); ?> 


4.1 对于这个例子,假设这个博客专门讨论关于汽车的信息。每个帖子描述了一辆特定的汽车(如1969年福特野马),并为每个帖子分配了三个自定义字段:制造商、型号和年份。此示例将显示文章标题,由特定制造商(福特)筛选,并按型号和年份排序。

<?php 
$meta_key1 = 'model';
$meta_key2 = 'year';
$meta_key3 = 'manufacturer';
$meta_key3_value = 'Ford';
$postids=$wpdb->get_col($wpdb->prepare("
SELECT      key3.post_id
FROM        $wpdb->postmeta key3
INNER JOIN  $wpdb->postmeta key1 
            on key1.post_id = key3.post_id
            and key1.meta_key = %s 
INNER JOIN  $wpdb->postmeta key2
            on key2.post_id = key3.post_id
            and key2.meta_key = %s
WHERE       key3.meta_key = %s 
            and key3.meta_value = %s
ORDER BY    key1.meta_value, key2.meta_value",$meta_key1, $meta_key2, $meta_key3, $meta_key3_value)); 
if ($postids) {
  echo 'List of ' . $meta_key3_value . '(s), sorted by ' . $meta_key1 . ', ' . $meta_key2;
  foreach ($postids as $id) { 
    $post=get_post(intval($id));
    setup_postdata($post);?>
    <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
    <?php
  } 
}
?>

4.2 此示例列出了包含特定自定义域但按第二个自定义域的值排序的所有日志。

<?php
//List all posts with custom field Color, sorted by the value of custom field Display_Order
//does not exclude any 'post_type'
//assumes each post has just one custom field for Color, and one for Display_Order
$meta_key1 = 'Color';
$meta_key2 = 'Display_Order';
$postids=$wpdb->get_col($wpdb->prepare("
SELECT      key1.post_id
FROM        $wpdb->postmeta key1
INNER JOIN  $wpdb->postmeta key2
            on key2.post_id = key1.post_id
            and key2.meta_key = %s
WHERE       key1.meta_key = %s
ORDER BY    key2.meta_value+(0) ASC",
         $meta_key2,$meta_key1)); 
if ($postids) {
  echo 'List of '. $meta_key1  . ' posts, sorted by ' . $meta_key2 ;
  foreach ($postids as $id) {
    $post=get_post(intval($id));
    setup_postdata($post);?>
    <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
    <?php
  }
}
?>


5.选择通用结果

<?php $wpdb->get_results('query', output_type); ?> 


5.1 获取用户 5 发布的草稿的id和标题,并显示标题。

$fivesdrafts = $wpdb->get_results("SELECT ID, post_title FROM $wpdb->posts
WHERE post_status = 'draft' AND post_author = 5");
foreach ($fivesdrafts as $fivesdraft) {
echo $fivesdraft->post_title;
}


5.2 获取用户 5 的所有草稿信息

<?php
$fivesdrafts = $wpdb->get_results("SELECT * FROM $wpdb->posts
WHERE post_status = 'draft' AND post_author = 5");
if ($fivesdrafts) :
foreach ($fivesdrafts as $post) :
setup_postdata($post);
?>
<h2><a href="<?php the_permalink(); ?>" rel="bookmark"
title="链接到 <?php the_title(); ?>"><?php the_title(); ?></a></h2>
<?php
endforeach;
else :
?>
    <h2> 未找到</h2>
<?php endif; ?>


6. 插入一行数据到数据表中

<?php $wpdb->insert( $table, $data, $format ); ?> 


6.0 在一行中插入两列,第一个值为字符串,第二个为数字:

$wpdb->insert( 'table', array( 'column1' => 'value1', 'column2' => 123 ), array( '%s', '%d' ) )


7. 更新数据库的记录。

<?php $wpdb->update( $table, $data, $where, $format = null, $where_format = null ); ?> 


7.0 更新ID为1的行,第一列的值为字符串,第二列的值为数组:

$wpdb->update( 'table', array( 'column1' => 'value1', 'column2' => 'value2' ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )


8. 防止SQL查询注入攻击

<?php $sql = $wpdb->prepare( 'query' [, value_parameter, value_parameter ... ] ); ?>


8.1  Add Meta key => value pair "Harriet's Adages" => "WordPress' database interface is like Sunday Morning: Easy." to Post 10.

$metakey = "Harriet's Adages";
$metavalue = "WordPress' database interface is like Sunday Morning: Easy.";
$wpdb->query( $wpdb->prepare( "
INSERT INTO $wpdb->postmeta
( post_id, meta_key, meta_value )
VALUES ( %d, %s, %s )", 
        10, $metakey, $metavalue ) );

8.2 The same query using vsprintf()-like syntax.

$metakey = "Harriet's Adages";
$metavalue = "WordPress' database interface is like Sunday Morning: Easy.";
$wpdb->query( $wpdb->prepare( "
INSERT INTO $wpdb->postmeta
( post_id, meta_key, meta_value )
VALUES ( %d, %s, %s )", 
        array(10, $metakey, $metavalue) ) );


9. 显示,打印.隐藏SQL错误

<?php $wpdb->show_errors(); ?> 

<?php $wpdb->hide_errors(); ?> 

<?php $wpdb->print_error(); ?> 


10. 获取列信息

<?php $wpdb->get_col_info('type', offset); ?> 


11. 使用 flush 清除SQL查询结果缓存

<?php $wpdb->flush(); ?>

可以清除 $wpdb->last_result, $wpdb->last_query, 和 $wpdb->col_info的缓存。


12. 类变量

$show_errors     # 是否打开 Error echoing. 默认为 TRUE.

$num_queries    #  已执行的查询的数量

$last_query        # 已执行的最后一条查询

$queries            # You may save all of the queries run on the database and their stop times by setting the SAVEQUERIES constant to TRUE (this constant defaults to FALSE). If SAVEQUERIES is TRUE, your queries will be stored in this variable as an array.

$last_result       # 最近的查询结果

$col_info          # 最新查询结果的列信息. 查阅 获取列信息章节.

$insert_id         # ID自动增长列生成的最近一条插入语句的ID

$num_rows      # 最近一个查询返回的行数

$prefix             # 表前缀


13. 多站点参数

如果你正在使用多站点, 你也可以访问:

$blogid   #  博客ID(多blog环境)


14. 数据表 

$posts                    # 文章表

$postmeta             # The Meta Content (a.k.a. Custom Fields) table.

$comments           # 评论表

$commentmeta    # The table contains additional comment information.

$terms                  # The terms table contains the 'description' of Categories, Link Categories, Tags.

$term_taxonomy   #  The term_taxonomy table describes the various taxonomies (classes of terms). Categories, Link Categories, and Tags are taxonomies.

$term_relationships   # The term relationships table contains link between the term and the object that uses that term, meaning this file point to each Category used for each Post.

$users                  # 用户表

$usermeta           # The usermeta table contains additional user information, such as nicknames, descriptions and permissions.

$links                   # 链接表


签名:这个人很懒,什么也没有留下!
最新回复 (0)
返回