Common methods of directly executing mysql query statements in wordpress

WordPress provides a kind of global variable called $wpdb that manipulates the data inventory. This global variable is used to associate with the WordPress database, so before we use it, we need to define this global variable. The writing method is as follows:

<?php  global $wpdb;  ?> 

Summary below

  • query: Execute a database query and return the number of results of the query.
  • get_row: The query returned multiple rows, but only the first row
  • get_results: return multiple rows of data

query function

To execute database query, you can execute any SQL query in the WordPress database through the query function. Select query only返回查询的结果数。

<?php $wpdb->query('query'); ?>
  
举个例子说明一下:删除ID13的文章。
<?php    $wpdb->query("DELETE FROM $wpdb->posts WHERE post_id = '13' ");  ?>

get_row function

To select a row of the table, you can use the get_row function. This function can return rows as objects, associative arrays, or numerically indexed arrays. If 查询返回了多个行,函数只返回第一行.

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

参数说明:
query :(字符串)你希望执行的查询语句。
output_type :三个预定义的常量之一。默认值为OBJECTOBJECT —— 返回的结果以对象形式输出,
			ARRAY_A ——返回的结果以关联数组形式输出,
			ARRAY_N —— 返回的结果以数值索引数组形式输出
row_offset:(整数)预计的数据库表的行数(0为表中第一行)。默认值为0

The example is as follows: Get all the information of the link with ID 10.

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

 //$mylink对象的属性即SQL查询结果的行名称(即$wpdb->links表中的所有行)。
 echo $mylink->link_id; // prints "10"
 
 //使用ARRAY_A
 $mylink = $wpdb->get_row("SELECT * FROM $wpdb->links WHERE link_id = 10", ARRAY_A);     

 //则会生成一个关联数组:
 echo $mylink['link_id']; // prints "10"     

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

 //则会生成一个数值索引数组:
 echo $mylink[1]; // prints "10"
?> 

get_results function

For query result sets, the get_results function can extract multiple rows of results generated by the function from the database. $wpdb function in array form返回整个查询结果。

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

参数说明:
query:(字符串)你希望执行的查询语句。将该参数设为null会使函数返回上一个查询的缓存结果中的信息。
output_type:三个预定义的常量之一,默认值为 OBJECTOBJECT —— 以对象形式输出返回的结果;
			ARRAY_A ——以关联数组形式输出返回的结果;
			ARRAY_N —— 以数值索引数组形式输出返回的结果。
 

Example description: Return all article content of the specified article type

<?php   
  $resaults = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_type = 'question'");  
  print_r($resaults);
?>  

Guess you like

Origin blog.csdn.net/weixin_44797182/article/details/114485105