简体   繁体   中英

PHP mysql error_log and immediately return a value

I'm writing a function that queries my database, and if the mysql query errors out for some reason, I'd like my function to return a value (in this case -1) indicating query failure, rather than dying out of the whole script.

Usually I just use this construct:

$result = mysql_query($sql) or die( [some error information] );

But in this case I don't want to die, but I do need to break out of the function and have some way to tell the calling function that something went wrong, while still being able to manually check the logs for the source of the error. Is there a way to do this? The semi-pseudocode would look something like:

$result = mysql_query($sql) or {
    error_log( [some error information] );
    return -1;
}

But I've tried a couple variations on that and (as one might expect) they don't work.

Any suggestions? Thanks.

Try this:

if(!($result = mysql_query($sql))) {
    error_log(...);
    return -1;
}

The or in that statement is one of PHP's logical operators which when used like that, will execute the second statement if the first one fails due to short circuit evaluation . You won't be able to return in that statement because you are doing assignment, and if you execute two statements, you won't be able to return a proper value to the $result variable.

You could do something like

$result = false or (error_log('message') && ($result = -1));
if ($result === -1) return $result;

but that isn't much shorter than anything else you can do.

Use an expression like what @Kolink provided to do what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM