返回的函数结果在条件语句中混淆


returned function result is confused in conditional statement

我有一个类的工作与数据库在PHP。这个类中的Add函数是:

    function Add($post_id)
    {
        if(!is_numeric($post_id))
        {
            return 1181;
        }
        $query  = "...";
        $result = mysql_query($query, $this->link);
        return $result;
    }

我还有一个获取表单数据并将它们传递给这个类的页面。页面代码为:

$result = $obj->Add($post_id);
if($result == 1181)
{
    echo 'invalid';
}
else if($result)
{
    echo 'success';
}
else
{
    echo 'error';
}

返回值为1,输出必须为"成功",但我得到"无效"消息。如果我交换"无效"answers"成功"条件语句,一切都很好,但我想知道这个问题是什么?

var_dump($result);是一个很好的起点。在布尔上下文中,1181将被转换为true,所以不要仅仅因为它打印了success就期望它成功了。

您可能通过了错误的post_id。启用显示警告和通知。不要使用疯狂的神奇常量,使用false或抛出异常。始终检查mysql_query的返回值

如果你这样做了,我就不用猜了,你可以取得进展,提出有意义的问题。

就像其他人在评论中指出的那样,您应该在这些类型的情况下使用exception。下面是一个例子。

function Add($post_id)
{
    if(!is_numeric($post_id))
    {
        throw new InvalidArgumentException( 'Argument should be numeric' );
    }
    $query  = "...";
    $result = mysql_query($query, $this->link); 
    return $result;
}
try
{
    $result = $obj->Add($post_id);
}
catch( InvalidArgumentException $e )
{
    /* handle the invalid argument exception */
}
if($result)
{
    echo 'success';
}
else
{
    echo 'error';
}

此外,如果你坚持用代码来表示你的错误,你可以这样写:

function Add($post_id)
{
    if(!is_numeric($post_id))
    {
        throw new InvalidArgumentException( 'Argument should be numeric', 1181 );
    }
    if($post_id <= 0)
    {
        throw new InvalidArgumentException( 'Argument should be larger than 0', 1182 );
    }
    $query  = "...";
    $result = mysql_query($query, $this->link); 
    return $result;
}
try
{
    $result = $obj->Add($post_id);
}
catch( InvalidArgumentException $e )
{
    switch( $e->getCode() )
    {
        case 1181:
            /* handle the invalid argument exception with code 1181 */
            break;
        case 1182:
            /* handle the invalid argument exception with code 1182 */
            break;
        default:
            /* handle other invalid argument exceptions */
            break;
    }
}

最后,就像其他人已经评论过的那样,异常处理与阻止SQL注入无关,也不会干扰。