vendredi 5 novembre 2021

When should I connect to my database with RedBean?

I'm in the process of making a signup and login system with RedBean, but I'm having some trouble trying to figure out when I should use R:setup();.

First and foremost I'm using R::setup at the top of my index page (even though I don't need to access my database from that page. Should I do this?).

Next, I'm using it in a functions file, from which I call some functions during signup and login:

function checkUidTaken ($uid) {

    require_once('../rb.php');
    R::setup('sqlite:database.sqlite');

    $uids = R::getCol('select uid from admins');

    if (in_array($uid, $uids)) {
        $result = true;
    } else {
        $result = false;
    }
    return $result;
};

function createAdmin ($name, $uid, $pwd) {

    require_once('../rb.php');
    R::setup('sqlite:database.sqlite');

    $pwd = password_hash($pwd, PASSWORD_DEFAULT);

    $admin = R::dispense('admins');
    
    $admin->name = $name;
    $admin->uid = $uid;
    $admin->pwd = $pwd;

    R::store($admin);

    header('location: ../admin-panel.php');
    exit();
};

As you can see, I'm calling it per function, but this causes an error.

A database has already been specified for this key.

As I understand, this is because I'm setting up my database twice in a row. I have tried to fix this by closing the database at the end of each function to no success.

If I leave out the first function, this system works. But then, at my login system I get the same error by setting up the database twice (as it is already setup during signup, and then during login).

If I don't setup my database, I get another error: Call to a member function isFrozen() on null

That is when I'm still requiring the rb.php.

Can you anwser me, when I'm supposed to setup my database? And how am I supposed to access it again when needed when already set up? Am I supposed to create a handle of some sort? If so, how?




Aucun commentaire:

Enregistrer un commentaire