【问题标题】:RedBean findOne failing?RedBean findOne 失败?
【发布时间】:2014-01-18 02:03:57
【问题描述】:

我正在使用 RedBean PHP ORM 来尝试注册/获取用户。也就是说,给定一个逗号分隔的列表,我会这样做

 $emails = explode(',', trim($app->request->post('emails')));

然后将每封邮件传递给这个函数

function registerOrGetUser($email)
{
    echo("R or G " . $email . "<br>");
    $user = R::findOne('user', ' email = ? ', array($email));
    if(!$user)
    {
        echo("Couldn't find user " . $email . ", creating new user.<br>");
        //user does not exist, register them
        $user = R::dispense('user');
        $password = $random = substr(md5(rand()),0,8);
        $user->email = $email;
        $user->password = md5($password);
        $user->role = 0;
        R::store($user);
        mail($user->email, "Welcome to imgstat!", "Welcome to imgstat, " . $user->email . "! An account has been created for you. Please sign in with this email address, and the following password: " . $password);
    }
    return $user;
}

注意调试的 echo 语句。我遇到的问题是它有时只能检测到用户是否已经存在。也就是说,如果我尝试添加

 test@test.test

它获取用户(并且不注册新用户)。但是,如果我尝试

 test@test.test, test@test.test

它在数据库中创建了第二个用户 - 据我所知,使用完全相同的电子邮件!从那时起,我可以根据需要添加任意数量的 test@test.tests - 他们将始终获取用户而不创建重复项。但由于某种原因,如果电子邮件不是逗号分隔列表中的唯一项目,则始终会创建第一个副本。

有什么想法吗?

【问题讨论】:

    标签: php mysql orm redbean


    【解决方案1】:

    注意空白。您的示例 test@test.test, test@test.test, test@test.test 完全符合您描述的问题。通过使用 ',' 分解该字符串,您会得到:

    Array
    (
        [0] => test@test.test
        [1] =>  test@test.test
        [2] =>  test@test.test
    )
    

    这就是为什么在使用邮件中的空间成功创建第二个用户并从那时起正确找到的原因。为防止出现空白,只需使用 registerOrGetUser(trim($email)) 调用您的函数

    【讨论】:

    • 啊,这更好 - 涵盖所有空白,而不仅仅是实际空格。谢谢!
    • 数据清理至关重要,您的查询也可能在 MySQL 中失败。
    【解决方案2】:

    找到了!

    愚蠢的错误 - 使用修剪只从列表的开头/结尾删除空格,所以有“test@test.com”和“test@test.com”...

    我的解决方法:

     $emails = explode(',', str_replace(' ', '', $app->request->post('emails')) );
    

    【讨论】:

      猜你喜欢
      • 2020-06-07
      • 2015-08-28
      • 2021-12-04
      • 2018-03-04
      • 2017-03-17
      • 1970-01-01
      • 1970-01-01
      • 2014-10-14
      • 1970-01-01
      相关资源
      最近更新 更多