转换if else尝试catch

aWe*_*per 1 php mysql if-statement try-catch

有人可以帮助我将使用if-else编写的以下代码转换为try/catch.另外让我知道在这种情况下需要trycatch或if-else是apt

$results = mysql_query($query);
if(mysql_num_rows($results)!=0)
{
    while(($result = mysql_fetch_row($results))!=FALSE)
    {
        $res   ="DELETE FROM table1 WHERE id ='".$result['id']."'";
        if(mysql_query($res)==false)
        {
            echo mysql_error();
            exit;
        }
    }
    echo $res   ="DELETE FROM table2 WHERE id ='".$id."'";
    if(mysql_query($res)!==false)
    {
        header("Location:list.php?m=4");
    }
    else
    {
        echo mysql_error();
        exit;
    }
}
else
{
    echo "Error";
}
Run Code Online (Sandbox Code Playgroud)

dec*_*eze 5

try...catch只有你的函数抛出异常才有意义.如果他们不这样做,那就什么都没有了catch.我从这开始作为重构:

$results = mysql_query($query);
if (!mysql_num_rows($results)) {
    echo 'No results!';
    exit;
}

$ids = array();
while (($result = mysql_fetch_row($results)) !== false) {
    $ids[] = $result['id'];
}

$ids = array_map('mysql_real_escape_string', $ids);
$query = "DELETE FROM table1 WHERE id IN ('" . join("','", $ids) . "')";
if (!mysql_query($query)) {
    echo mysql_error();
    exit;
}

$query = "DELETE FROM table2 WHERE id = '$id'";
if (!mysql_query($query)) {
    echo mysql_error();
    exit;
}

header("Location: list.php?m=4");
exit;
Run Code Online (Sandbox Code Playgroud)

这仍然可以改进很多,但它已经比你的意大利面条逻辑有所改进.如果您对正确使用异常非常感兴趣,那么首先应该继续正确使用重复任务的函数(比如error, exit部分),然后可能将整个事物重组为类和对象,最后使用异常在现在嵌套之间进行通信层.也许开始使用PHP框架来感受整个事情.

将异常放入上面的代码只不过是一个goto,但仅用于说明目的:

try {

    $results = mysql_query($query);
    if (!mysql_num_rows($results)) {
        throw new Exception('No results!');
    }

    $ids = array();
    while (($result = mysql_fetch_row($results)) !== false) {
        $ids[] = $result['id'];
    }

    $ids = array_map('mysql_real_escape_string', $ids);
    $query = "DELETE FROM table1 WHERE id IN ('" . join("','", $ids) . "')";
    if (!mysql_query($query)) {
        throw new Exception(mysql_error());
    }

    $query = "DELETE FROM table2 WHERE id = '$id'";
    if (!mysql_query($query)) {
        throw new Exception(mysql_error());
    }

    header("Location: list.php?m=4");
    exit;

} catch (Exception $e) {

    echo 'ERROR: ' . $e->getMessage();
    exit;

}
Run Code Online (Sandbox Code Playgroud)