How do you trigger_error() to a variable?

I’m trying to trigger a PHP error when something happens. Here’s my code:

try {
/*LIST OF MYSQL QUERIES HERE*/
if($result->num_rows === 0) {
	trigger_error("There was a problem."); /*THIS NEEDS TO TRIGGER THE $e VARIABLE, BUT IT DOESN'T*/
	};
} catch (Throwable $e) {
    $mysqli->rollback();
    if (strpos($e, "There was a problem") !== false) {
    echo "Yay! My error was triggered";
    }
}

If a mysql query is unsuccessful, the $e holds the error, but if I trigger an error, it just exists the code at that line and prints the error. I need it to be stored inside the $e variable that is “caught” in the catch block. How do I accomplish this?

I noticed that this works:

throw new Exception("There was a problem.");

Is this the correct way to throw an error in a try-catch situation like mine?

There are two ways of handling errors in PHP; errors (which use trigger_error) and exceptions (which use the throw / catch syntax). You can use either, but it’s best not not mix them.

I prefer exceptions and they’re more commonly used. You may find your database module can be configured to throw them automatically.

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service