日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

黄聪:使用Wordpress中的wpdb类操作数据库

發(fā)布時(shí)間:2025/3/20 数据库 50 豆豆
生活随笔 收集整理的這篇文章主要介紹了 黄聪:使用Wordpress中的wpdb类操作数据库 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

WordPress包含一個(gè)操作數(shù)據(jù)庫的類——wpdb,該類基于ezSQL(由Justin Vincent維護(hù)的數(shù)據(jù)庫操作項(xiàng)目)編寫,包含了其基本的功能。

使用說明

請不要直接調(diào)用wpdb類中的方法。WordPress定義了$wpdb的全局變量,所以請直接調(diào)用該全局變量$wpdb的實(shí)例來操作數(shù)據(jù)庫。(調(diào)用之前不要忘了聲明引用全局變量$wpdb。參考globalize)

$wpdb對象可以用來操作WordPress數(shù)據(jù)庫中的每一個(gè)表,不僅僅是WordPress自動(dòng)創(chuàng)建的基本表。例如,你有一個(gè)自定義的表叫做mytable,那么可以使用如下語句來查詢:?

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

?

$wpdb對象可以讀取多個(gè)表,但是其只針對WordPress的數(shù)據(jù)庫。如果你需要連接其他數(shù)據(jù)庫,那么你應(yīng)該使用你自己的數(shù)據(jù)庫連接信息,并調(diào)用wpdb類來創(chuàng)建一個(gè)你自己的數(shù)據(jù)庫操作實(shí)例。如果你有多個(gè)數(shù)據(jù)庫需要連接,那么你可以考慮使用hyperdb來替代$wpdb。

在數(shù)據(jù)庫上運(yùn)行任務(wù)查詢

這個(gè)查詢函數(shù)允許你在wordpress的數(shù)據(jù)庫里運(yùn)行任何SQL查詢。當(dāng)然了,最好能利用如下的特定函數(shù),

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

query?
(string) 你需要執(zhí)行的SQL查詢

此函數(shù)返回操作/查詢的行或列的整數(shù)。如果出現(xiàn)了MySQL錯(cuò)誤,此函數(shù)將返回?FALSE(注意: 因?yàn)?0 和 FALSE 都可能被返回, 確保你使用了正確的比較運(yùn)算符:等于?==?vs. 一致?===)。

注意:As with all functions in this class that execute SQL queries, you must SQL escape all inputs (e.g.,?wpdb->escape($user_entered_data_string)). See the section entitled?Protect Queries Against SQL Injection Attacks?below.

示例

刪除屬于id為13的文章的‘gargle’meta 鍵和值。

$wpdb->query("DELETE FROM $wpdb->postmeta WHERE post_id = '13'AND meta_key = 'gargle'");

在WordPress中由?delete_post_meta()執(zhí)行.


設(shè)置頁面?Page?15 的父級頁面為 7.

$wpdb->query("UPDATE $wpdb->posts SET post_parent = 7WHERE ID = 15 AND post_status = 'static'");

選擇一個(gè)變量

The?get_var?function returns a single variable from the database. Though only one variable is returned, the entire result of the query is cached for later use. Returns?NULL?if no result is found.

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

query?
(string) The query you wish to run. Setting this parameter to?null?will return the specified variable from the cached results of the previous query.
column_offset?
(integer) The desired column (0?being the first). Defaults to?0.
row_offset?
(integer) The desired row (0?being the first). Defaults to?0.

示例

獲取并顯示用戶數(shù)量

<?php $user_count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $wpdb->users;")); echo '<p>User count is ' . $user_count . '</p>'; ?>

獲取并顯示?自定義字段值?的總和.

<?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>'; ?>

選擇一行

To retrieve an entire row from a query, use?get_row. The function can return the row as an object, an associative array, or as a numerically indexed array. If more than one row is returned by the query, only the specified row is returned by the function, but all rows are cached for later use. Returns NULL if no result is found.

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

query?
(string) The query you wish to run.
output_type?
One of three pre-defined constants. Defaults to OBJECT.
  • OBJECT - result will be output as an object.
  • ARRAY_A - result will be output as an associative array.
  • ARRAY_N - result will be output as a numerically indexed array.
row_offset?
(integer) The desired row (0?being the first). Defaults to?0.

示例

獲取ID為10的鏈接的全部信息

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

$mylink對象的屬性是SQL查詢結(jié)果的列名(此例中是所有?$wpdb->links表中的列名)。

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

作為對比, 使用

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

將返回關(guān)聯(lián)數(shù)組:

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

然后

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

將返回索引數(shù)組:

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

選擇一列

To SELECT a column, use?get_col. This function outputs a dimensional array. If more than one column is returned by the query, only the specified column will be returned by the function, but the entire result is cached for later use. Returns an empty array if no result is found.

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

query?
(string) the query you wish to execute. Setting this parameter to?null?will return the specified column from the cached results of the previous query.
column_offset?
(integer) The desired column (0?being the first). Defaults to?0.

示例

For this example, assume the blog is devoted to information about automobiles. Each post describes a particular car (e.g. 1969 Ford Mustang), and three?Custom Fields, manufacturer, model, and year, are assigned to each post. This example will display the post titles, filtered by a particular manufacturer (Ford), and sorted by model and year.

The?get_col?form of the?wpdb Class?is used to return an array of all the post ids meeting the criteria and sorted in the correct order. Then a?foreach?construct is used to iterate through that array of post ids, displaying the title of each post. Note that the SQL for this example was created by?Andomar.

<?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_idand key1.meta_key =?%s INNER JOIN $wpdb->postmeta key2on key2.post_id = key3.post_idand 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} } ?>

This example lists all posts that contain a particular custom field, but sorted by the value of a second custom field.

<?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 key2on key2.post_id = key1.post_idand 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} } ?>

選擇通用結(jié)果

Generic, mulitple row results can be pulled from the database with?get_results. The function returns the entire query result as an array. Each element of this array corresponds to one row of the query result and, like?get_row, can be an object, an associative array, or a numbered array.

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

query?
(string) The query you wish to run. Setting this parameter to?null?will return the data from the cached results of the previous query.
output_type?
One of four pre-defined constants. Defaults to OBJECT. See?SELECT a Row?and its examples for more information.
  • OBJECT - result will be output as a numerically indexed array of row objects.
  • OBJECT_K - result will be output as an associative array of row objects, using first column's values as keys (duplicates will be discarded).
  • ARRAY_A - result will be output as an numerically indexed array of associative arrays, using column names as keys.
  • ARRAY_N - result will be output as a numerically indexed array of numerically indexed arrays.

Since this function uses the '$wpdb->query()' function all the class variables are properly set. The results count for a 'SELECT' query will be stored in $wpdb->num_rows.

示例

獲取用戶 5 發(fā)布的草稿的id和標(biāo)題,并顯示標(biāo)題。

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

獲取用戶 5 的所有草稿信息

<?php $fivesdrafts = $wpdb->get_results("SELECT * FROM $wpdb->postsWHERE 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> <?phpendforeach; else?: ?><h2> 未找到</h2> <?php endif;??>

插入行

插入一行數(shù)據(jù)到數(shù)據(jù)表中

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

table?
(string) 插入數(shù)據(jù)的數(shù)據(jù)表名稱。
data?
(array) 插入的數(shù)據(jù) (為 column => value 鍵值對). $data columns 和 $data values 都可以是 "raw" 數(shù)據(jù) (neither should be SQL escaped).
format?
(array|string) (optional) An array of formats to be mapped to each of the value in $data. If string, that format will be used for all of the values in $data. If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.

Possible format values:?%s as string;?%d as decimal number; and?%f as float.

After insert, the ID generated for the AUTO_INCREMENT column can be accessed with:

$wpdb->insert_id

如果不能插入行,此函數(shù)返回false

示例

在一行中插入兩列,第一個(gè)值為字符串,第二個(gè)為數(shù)字:

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

更新記錄

更新數(shù)據(jù)庫的記錄。

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

table?
(string) 要更新的表名稱。
data?
(array) 需要更新的數(shù)據(jù)(使用格式:column => value)。Both $data columns and $data values should be "raw" (neither should be SQL escaped).
where?
(array) A named array of WHERE clauses (in column => value pairs). Multiple clauses will be joined with ANDs. Both $where columns and $where values should be "raw".
format?
(array|string) (optional) An array of formats to be mapped to each of the values in $data. If string, that format will be used for all of the values in $data.
where_format?
(array|string) (optional) An array of formats to be mapped to each of the values in $where. If string, that format will be used for all of the items in $where.

Possible format values:?%s as string;?%d as decimal number and?%f as float. If omitted, all values in $where will be treated as strings.

示例

更新ID為1的行,第一列的值為字符串,第二列的值為數(shù)組:

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

防止SQL查詢注入攻擊

For a more complete overview of SQL escaping in WordPress, see?database Data Validation. That?Data Validationarticle is a?must-read?for all WordPress code contributors and plugin authors.

Briefly, though, all data in SQL queries must be SQL-escaped before the SQL query is executed to prevent against SQL injection attacks. This can be conveniently done with the?prepare?method, which supports both asprintf()-like and?vsprintf()-like syntax.

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

query?
(string) The SQL query you wish to execute, with?%s?and?%d?placeholders. Any other?%?characters may cause parsing errors unless they are escaped. All?%?characters inside SQL string literals, including LIKE wildcards, must be double-% escaped as?%%.
value_parameter?
(int|string|array) The value to substitute into the placeholder. Many values may be passed by simply passing more arguments in a?sprintf()-like fashion. Alternatively the second argument can be an array containing the values as in PHP's?vsprintf()?function. Care must be taken not to allow direct user input to this parameter, which would enable array manipulation of any query with multiple placeholders. Values must not already be SQL-escaped.

示例

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

Performed in WordPress by?add_meta().

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

Note that in this example we pack the values together in an array. This can be useful when we don't know the number of arguments we need to pass until runtime.

Notice that you do not have to worry about quoting strings. Instead of passing the variables directly into the SQL query, use a?%s?placeholder for strings and a?%d?placedolder for integers. You can pass as many values as you like, each as a new parameter in the?prepare()?method.

顯示和隱藏SQL錯(cuò)誤

You can turn error echoing on and off with the?show_errors?and?hide_errors, respectively.

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

You can also print the error (if any) generated by the most recent query with?print_error.

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

獲取列信息

You can retrieve information about the columns of the most recent query result with?get_col_info. This can be useful when a function has returned an OBJECT whose properties you don't know. The function will output the desired information from the specified column, or an array with information on?all?columns from the query result if no column is specified.

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

type?
(string) What information you wish to retrieve. May take on any of the following values (list taken from theezSQL docs). Defaults to?name.
  • name - column name. Default.
  • table - name of the table the column belongs to
  • max_length - maximum length of the column
  • not_null - 1 if the column cannot be NULL
  • primary_key - 1 if the column is a primary key
  • unique_key - 1 if the column is a unique key
  • multiple_key - 1 if the column is a non-unique key
  • numeric - 1 if the column is numeric
  • blob - 1 if the column is a BLOB
  • type - the type of the column
  • unsigned - 1 if the column is unsigned
  • zerofill - 1 if the column is zero-filled
offset?
(integer) Specify the column from which to retrieve information (with?0?being the first column). Defaults to-1.
  • -1 - Retrieve information from all columns. Output as array. Default.
  • Non-negative integer - Retrieve information from specified column (0?being the first).

清除緩存

使用?flush?清除SQL查詢結(jié)果緩存

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

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

類變量

$show_errors?
是否打開?Error echoing. 默認(rèn)為 TRUE.
$num_queries?
已執(zhí)行的查詢的數(shù)量
$last_query?
已執(zhí)行的最后一條查詢
$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?
最近的查詢結(jié)果
$col_info?
最新查詢結(jié)果的列信息. 查閱?獲取列信息章節(jié).
$insert_id?
ID自動(dòng)增長列生成的最近一條插入語句的ID
$num_rows?
最近一個(gè)查詢返回的行數(shù)
$prefix?表前綴$last_error錯(cuò)誤信息

多站點(diǎn)參數(shù)

如果你正在使用多站點(diǎn), 你也可以訪問:

$blogid?
博客ID(多blog環(huán)境)

數(shù)據(jù)表

The WordPress database tables are easily referenced in the?wpdb?class.

$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?
鏈接表
$options?
The?Options?table.

總結(jié)

以上是生活随笔為你收集整理的黄聪:使用Wordpress中的wpdb类操作数据库的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。