【问题标题】:Write to database, and retrieve updated data in the same PHP page load?写入数据库,并在同一 PHP 页面加载中检索更新的数据?
【发布时间】:2019-01-21 12:04:21
【问题描述】:

我的网站在 WordPress 上运行,并包含一个像这样工作的帐户激活系统:

  1. 用户创建帐户,立即登录并显示主页。
  2. 一个函数检查数据库以查看帐户是否已激活,如果没有,则在主页上显示一条消息,要求单击验证电子邮件中的链接。
  3. 用户打开他们的电子邮件并单击激活链接。 (例如:https://example.com/?action=activate&user=swen&key=1234
  4. 打开此页面时,函数会检查是否设置了 action 参数并运行帐户激活函数,然后将帐户更新为“已激活”。
  5. WP的其余部分都执行了,但是检查账户激活的功能仍然显示账户没有被激活。
  6. 在没有查询变量的情况下再次浏览 https://example.com 时,消息消失,表明上述示例 URL 实际上确实可以激活帐户。

是否有可能将数据写入数据库和检索相同的更新数据之间的时间太短?


更新:

想知道 MySQL 是否在同一个页面加载中缓存数据。我尝试在检索更新的用户角色之前刷新 WordPress 缓存,但没有成功。

检查 URL 并运行 activate_user 函数的操作:

我尝试使用 setup_theme 挂钩尽早执行此操作,以确保它在加载主题之前运行。

add_action('setup_theme', 'ns_activate_user_action');
function ns_activate_user_action() {
    // Check if all action parameters are present
    if ( !ns_validate_action('activate', array('user', 'key')) ) {
        return;
    }

    // Activate user by key, runs the "activate_user" function
    $activate_user = activate_user_by_key($_GET['user'], $_GET['key']);

    // At this point the user role should have changed
    // and the account be activated
}

激活帐户的功能:

function activate_user($user) {
    // ...

    $user->add_role( 'member' );
    $user->remove_role( 'member_pending' );

    // ...

    return $user;       
}

检查帐户是否激活的功能:

function is_user_activated($user) {

    // ...

    if ( in_array( 'member_pending', (array) $user->roles ) ) {
        return false;
    }

    return true;
}

自定义操作显示激活消息,在主题文件中使用do_action() 调用:

add_action('ns_after_header', 'ns_activate_account_notice_front_page');
function ns_activate_account_notice_front_page() {
    if ( is_user_logged_in() && is_front_page() && !is_user_activated() ) {
        // ... Echos message asking user to click activation link in email
        // Checking the user role here with wp_get_current_user()->roles
        // still shows that the user is in the "member_pending" role (inactive)
    }
}

【问题讨论】:

  • 只要在从数据库中拉取数据之前完成插入,你应该得到一个最新的版本。
  • @GrumpyCrouton 这就是我的想法,但似乎并非如此。
  • 显示您的代码。你怎么更新这个?你使用 $wpdb 吗?还是 update_option 函数?还是更新元数据?
  • @Blackbam 添加了我的代码。

标签: php mysql database wordpress


【解决方案1】:

我会尝试使用 add_action 优先级。由于您没有在 add_action 函数中指定它们,因此它们都默认为十(10)。

https://developer.wordpress.org/reference/functions/add_action/

这似乎是他们的完美用例

【讨论】:

    【解决方案2】:

    事实证明,这是 WordPress 的问题,很可能与缓存有关。查看这个问题,了解为什么会发生这种情况以获取更多信息。

    Updated user role inncorrect when using wp_get_current_user()

    回答我自己的问题:

    是的,您可以写入数据库,并在同一个 PHP 页面加载中检索更新的信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-23
      • 1970-01-01
      • 2014-08-27
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-14
      相关资源
      最近更新 更多