This issue is typically caused by the caching mechanism used in WordPress. When you perform an update operation in WordPress, the $wpdb object stores the data in memory; when the same data is queried again, it retrieves the data from memory instead of fetching it from the database. While this caching mechanism can improve query performance, it may also lead to the situation where data does not update immediately after an update is performed.
To resolve this issue, you can force a refresh of the $wpdb object's cache after updating the data, ensuring that the next query retrieves the latest data from the database. In WordPress, you can achieve this using the `flush()` method. Here is an example:
<?php
// 引入WordPress的核心文件
require_once( dirname( __FILE__ ) . '/wp-load.php' );
// 更新数据
global $wpdb;
$table_name = $wpdb->prefix . 'my_table'; // 获取表名
$data = array(
'name' => 'John',
'email' => 'john@example.com'
);
$where = array( 'id' => 1 );
$wpdb->update( $table_name, $data, $where );
// 刷新缓存
$wpdb->flush();
// 查询数据
$results = $wpdb->get_results( "SELECT * FROM $table_name WHERE id = 1" );
// 输出查询结果
if ( $results ) {
$row = $results[0];
echo $row->name . ': ' . $row->email;
} else {
echo 'No results found';
}In this example, after updating the data, we call the `flush()` method on the `$wpdb` object to force a cache refresh. Then, we execute the query again and output the query results. Now, you should be able to see the latest updated data.
Please note that refreshing the cache may impact performance, as it forces the $wpdb object to fetch the latest data from the database. If your query operations are frequent and you have high performance requirements, it is recommended to use the caching mechanism provided by WordPress to reduce the number of database accesses.