简体   繁体   English

PHP mysql error_log并立即返回值

[英]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. 我正在编写一个查询数据库的函数,如果mysql查询由于某种原因而出错,我希望我的函数返回一个表示查询失败的值(在这种情况下为-1),而不是全部消失脚本。

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 . 该语句中的or是PHP的逻辑运算符之一 ,当这样使用时,如果第一个语句由于短路评估而失败,它将执行第二个语句。 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. 由于正在执行赋值操作,因此您将无法return该语句;如果执行两个语句,您将无法向$result变量返回正确的值。

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. 使用类似@Kolink提供的表达式来执行所需的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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