运行php代码时出错

时间:2013-11-06 08:44:52

标签: php web-services fatal-error

我正在制作一个小型PHP应用程序,它使用一些数据来检查它是否与数据库的记录匹配(登录过程的原型),但是它给了我一个(额外的垃圾数据错误)并且在评论时标题行检查错误,它给了我致命的错误:

致命错误:第22行的C:\ wamp \ www \ hh \ login.php超出了30秒的最长执行时间

守则:

<?php

header("Content-type: text/xml");

$host = "localhost";
$user = "muhammed";
$pass = "";
$database = "test";

$linkID = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $linkID) or die("Could not find database.");

$query = "SELECT * FROM info";
$resultID = mysql_query($query, $linkID) or die("Data not found.");

$name = "tahany";
$age  = 90;

while(true){
for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++){
    $row = mysql_fetch_assoc($resultID);
    if ($row['Name'] == $name && $row['age'] == $age){
        $res = "login success";
        break;
    }else{
        $res = "failed to login";
    }
}
}

echo $res;

?>

5 个答案:

答案 0 :(得分:2)

您需要优化代码,不需要额外的for loop

while($row=mysql_fetch_assoc($resultID)){
    if ($row['Name'] == $name && $row['age'] == $age){
        $res = "login success";
    }else{
        $res = "failed to login";
    }
}


注意: mysql_*函数已弃用mysqli_*函数asap。

答案 1 :(得分:1)

You getting fatal error because of infinite loop you are putting break in inner loop but outer loop is infinite.

答案 2 :(得分:1)

您可以(并且应该)从代码中删除while (true)语句。这不是必需的。这就是造成你的超时的原因。 break语句只会破坏内部for - 循环,而不会破坏外部while循环。

现在,修复while循环可能是这样的:

$break_loop = false;
while (!$break_loop ) {
    // Keep your existing code as-is.
    for (...) {
        if (...) {
            ...
        } else {
            ...
        }
    }

    // Always break the loop, whether or not the log-in was successful. 
    // We need to stop the while-loop anyhow.
    //
    // When the log-in was successful, we jumped out of the for-loop much
    // sooner.
    $break_loop = true;
}

因此我们使用临时变量来保持循环运行,直到变量设置为true。当我们在登录成功或所有尝试都失败时跳出for - 循环时会发生这种情况。

但同样,不需要while - 循环,因为您的for - 循环已经处理它。

答案 3 :(得分:1)

使用此代码并不好,但它很有用 休息2;

http://php.net/manual/en/control-structures.break.php

答案 4 :(得分:0)

如果需要增加PHP脚本的时间。这样做

<?php
set_time_limit(0);

实际问题在于你的while循环。

您的while循环在无限条件下运行。尝试改变它。永远记得while(true)无限奔跑。

$i=0;
while($i==0){
for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++){
    $row = mysql_fetch_assoc($resultID);
    if ($row['Name'] == $name && $row['age'] == $age){
        $res = "login success";
        break;
    }else{
        $res = "failed to login";
    }
}
$i=1; // Changing the flag to 1 , so while condition fails
}