PDOExceptions and Bools

Your getting there. Just keep learning.

In your current class siteHTTP the else is not needed. Just do like so…

if (!$stmt = $this->pdo->query($sql)) {
    return false;
}

return $stmt->fetch()['http_request'];
1 Like

NO. You are writing out a method for each piece of data. If you add a new data value, you should NOT need to touch the code. If you had 30 different settings, do you think writing out 30 different methods would be a good idea? You should have either a (one) general-purpose get method, that accepts the setting name as an input parameter or you should use a magic __get() method. You should also not have a column for each setting. You should instead have a separate row for each setting.

Since you are using exceptions for database statement errors, if the ->query() method call in that code fails, execution transfers to the nearest PDO exception handler, or to php if there is no specific PDO exception handler. There’s no point in the if() conditional logic or the return false statement since that code is not executed upon an error.

One of the points about using exceptions is that your ‘main’ code only has to deal with error free execution, since execution transfers elsewhere upon an error, simplifying your code. There’s no need for any conditional logic testing returned values and the only time you should have a try/catch block is when its possible to ‘recover’ from an error, such as when inserting/updating duplicate or out of range user data.

OK I will work on that…

Some times i do need a return of true or false and here is an example…
In its own class to seperate. I dont want to load all my classes at once i only load them where i need them. Would i use an array of Name values to put into it then(regarding above post about my settings)? Where would i keep that array? inside that class at the top ? or in the Function?
I check if the users session id is genuine if not return false…

class checkUserSessionID {

    private $pdo;

    public function __construct(PDO $pdo) {

        $this->pdo = $pdo;

    }

    // Site account sessions

    public function sidCheck($username, $sid) {

        //check that the username and password match and return true or false

        $stmt = $this->pdo->prepare('SELECT sessionid FROM users WHERE username = ?');

        if ($stmt->execute([$username]) && password_verify($sid, $stmt->fetch()['sessionid'])) {

            return true;

        } else {

            return false;

        }

    }

}

and in my main file

require_once INCLUDES_BASEDIR.'_site_pdo/_sitePDO-checkUserSessionID.class.php';

    $verifyUserSessionID = new checkUserSessionID($sitePDO);

    ////////////////////////////////////////////

    // Check the users Session ID matches the Session ID in the database

    if (!$verifyUserSessionID->sidCheck($_SESSION['username'], $_SESSION['sessionid'])) {

        // This will only be called if a users active session ID

        // changes in the database due to logging into another device or an intruder

        // Session does not exist

        logout($sessionUpdateID, 'MIN');

        header('Location: '.SITE_URL.'?sysmsg=sidinvalid'.$sysMsgCon.$randSysMsgID);

        exit;

    }

If i don’t have the if statement how would i know the users session id didon’t match?? That applies to the function above.

Generaly i need to know if my PDO $stmt was true or false…

7 Answers. Method is actually a function used in the context of a class/object. When you create a function outside of a class/object, you can call it a function but when you create a function inside a class, you can call it a method . So an object can have methods ( functions ) and properties (variables). That’s from stack overflow on a google search… And is how i referenced it above.

The 2nd and 3rd paragraphs I wrote in that reply have to do with using exceptions for database statement errors, and they were with respect to the previous code you posted. They don’t have anything to do with your application logic.

No, you don’t. Do you even know what would cause $stmt to be a false value or what would cause $stmt->execute([$username]) to be a false value?

I suspect you think that a query that matches no data produces an error. It does not. It is a successful query that just has no rows in the result set.

Some of the things that would cause $stmt or$stmt->execute([$username]) to be a false value -

  1. No database selected.
  2. An sql syntax error.
  3. Wrong table/column names.
  4. Inserting/updating duplicate values, out of range values, or null values where nulls are not allowed.

Items 1-3 are programming mistakes. Item 4 has to do with wrong data values, some of which are programming mistakes and in the case of a duplicate value is something that your code should detect and attempt to recover from.

In the last code you posted, including $stmt->execute([$username]) in the conditional test is pointless. When using exceptions for errors, if the ->execute() call produced an error, program execution goes to the nearest PDO exception handler, and all the rest of the code in that method is not executed. Your conditional test should only be concerned with the value from password_verify().

1 Like

No worries, errors and exceptions aside for a minute…

Is this what you mean?

public function sidCheck($username, $sid) {

        $stmt = $this->pdo->prepare('SELECT sessionid FROM users WHERE username = ?');

        $stmt->execute([$username]);

        return password_verify($sid, $stmt->fetch()['sessionid']);

    }

}

EDIT: syntex error fixed.

And this would still give me a true or false answer? and i can still use my if statement in the main file to check if the session is genuine?

Back to exceptions and errors how can i catch all errors or exceptions into one dynamic catch? is that silly? I could then send errors and exceptions to my email and warnings can be handled in my code with the one time message session i made…

as for #4

I do that logic away from database code. Like checking if a post is empty or has the right value befor i send it to the pdo class’s… All gets filtered etc as well

thats what u mean?

ALSO now this should look like this… and i need to implement this through the rest of my site??

class siteHTTP {

    private $pdo;

    public function __construct(PDO $pdo) {

        $this->pdo = $pdo;

    }

    // Select HTTP request

    public function request() {

        $sql = "SELECT http_request FROM settings WHERE 1";

        $stmt = $this->pdo->query($sql);

        return $stmt->fetch()['http_request'];

        

    }

    //#

    // Select Domain

    public function domain() {

        $sql = "SELECT site_domain FROM settings WHERE 1";

        $stmt = $this->pdo->query($sql);

        return $stmt->fetch()['site_domain'];

    }

    //#

    // Select Directory

    public function directory() {

        

        $sql = "SELECT site_url_dir FROM settings WHERE 1";

        $stmt = $this->pdo->query($sql);

        return $stmt->fetch()['site_url_dir'];

    }

    //#

}

and if empty or wrong value in my main file i can deal with it there??

Sponsor our Newsletter | Privacy Policy | Terms of Service