mardi 7 mars 2017

Best practice for MySQL results with functions

I am currently using a function to grab all user's info and then complete some stages. I was wondering if it is not the best way to do this.

What I am currently using

function GetUserInfo()
{
    if(!$this->DBLogin())
    {
        $this->HandleError("Database login failed!");
        return false;
    }

    $conn = $this->connection;
    $query = "SELECT * FROM $this->tablename WHERE account=?";
    $query = $conn->prepare($query);
    $query->execute([$_SESSION['uid']]);
    $row = $query->fetch();

    return $row;
}

And then

if ($row['status'] == 0)
{
    // Do something here
}
elseif ($row['info'] == "Bazinga")
{
    // Do something here
}
else
{
    // Do something here
}

And the alternative I was thinking was something like this (plus add more functions for verifying each stage)

function CheckStageA()
{
    if(!$this->DBLogin())
    {
        $this->HandleError("Database login failed!");
        return false;
    }
    $conn = $this->connection;
    $query = "SELECT status FROM $this->tablename WHERE account=?";
    $query = $conn->prepare($query);
    $query->execute([$_SESSION['uid']]);
    $row = $query->fetch();
    if($row['status'] == 0)
    {
        return false;
    }

    return true;
}

With something like this

if ($checking->CheckStageA())
{
    // Do something here
}
elseif ($checking->CheckStageB())
{
    // Do something here
}
else
{
    // Do something here
}

Ok the alternative I am thinking requires a ton more coding but maybe it is a more proper way to do it.

Aucun commentaire:

Enregistrer un commentaire