PHP没有捕获sql错误

时间:2015-07-01 05:25:38

标签: php

我有一个脚本来管理用户登录,当用户名被输入到字段中并且密码被输入到它的字段中时它们与你登录的数据库相匹配,如果没有你得到的话由登录表单解析返回的错误。但是当你在用户名中输入一个无效的值(一个不存在的用户名)时,代码就不会继续,所以如何解决?

<?php

require("bootstrap.php");

$con=mysql_connect(DB_HOST,DB_USER_SEC,DB_PASS_SEC) or die("Failed to connect to MySQL: " . mysql_error());

$db=mysql_select_db(DB_NAME_SEC,$con) or die("Failed to connect to MySQL: " . mysql_error());

$query = mysql_query("SELECT * FROM username WHERE userName = '$_POST[username]'") or die(mysql_error());

if(!empty($_POST['username']))
{
    if(!empty($_POST['password']))
    {
        $row = mysql_fetch_array($query) or die(mysql_error());
        if(!empty($row['userName']))
        {
            if(!empty($row['userPass']))
            {
                if($_POST['password'] === $row['userPass'])
                {
                    session_start();
                    $_SESSION['logged']       = true;
                    $_SESSION['userName']     = $row['userName'];
                    $_SESSION['fname']        = $row['fname'];
                    $_SESSION['mname']        = $row['mname'];
                    $_SESSION['lname']        = $row['lname'];
                    $_SESSION['primnum']      = $row['primnum'];
                    $_SESSION['secnum']       = $row['secnum'];
                    $_SESSION['department']   = $row['department'];
                    $_SESSION['clearance']    = $row['clearance'];
                    $_SESSION['theme']        = $row['theme'];
                    $_SESSION['animations']   = $row['animations'];
                    $_SESSION['gtag']         = $row['gtag'];

                    header("Location: /workspace/index");
                }
                else
                {
                    session_start();

                    $_SESSION['logged']       = false;
                    $_SESSION['err']          = "0x001";

                    header("Location: /login");
                }
            }
            else
            { 
                session_start();

                $_SESSION['logged']       = false;
                $_SESSION['err']          = "0x005";

                header("Location: /login");
            }
        }
        else
        { 
            session_start();

            $_SESSION['logged']       = false;
            $_SESSION['err']          = "0x002";

            header("Location: /login");
        }
    }
    else
    {
        session_start();

        $_SESSION['logged']       = false;
        $_SESSION['err']          = "0x003";

        header("Location: /login");
    }
}
else
{
    session_start();

    $_SESSION['logged']       = false;
    $_SESSION['err']          = "0x004";

    header("Location: /login");
}

?>

是的我知道MySqli和PDO所以请不要带上它。

1 个答案:

答案 0 :(得分:1)

此行使代码停止

$row = mysql_fetch_array($query) or die(mysql_error());

如果没有要获取的行,则基本上mysql_fetch_array($ query)返回false。 所以它将落入死亡声明