Question

I am using the RedBean PHP ORM to try and register/get users. That is, given a comma separated list, I do

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

And then pass each email to this function

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

Note the echo statement for debug. The issue I am having is that it is only sometimes able to detect whether or not the user already exists. That is, if I try to add

 test@test.test

it gets the user (and does not register a new one). However, if I try

 test@test.test, test@test.test

it creates a SECOND user in the database - with, as far as I can tell, the exact same email! From then on, I can add as many test@test.tests as I want - they will always get the user and not create duplicates. But for some reason, that first duplicate is ALWAYS created if the email is not the only item in the comma separated list.

Any ideas?

Was it helpful?

Solution

Watch out for white-space. Your example test@test.test, test@test.test, test@test.test perfectly fits the problem you described. By exploding that string with ',' you'd get:

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

That's why after creating the second user with the space in the mail succeeded and was correctly found from then on. To prevent white space, just call your function with registerOrGetUser(trim($email))

OTHER TIPS

Found it!

Stupid mistake - using trim only removes whitespace from the start/end of the list, so there was " test@test.com" and "test@test.com"...

My fix:

 $emails = explode(',', str_replace(' ', '', $app->request->post('emails')) );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top