PHP跳过块

时间:2016-07-01 07:26:57

标签: php mysql database if-statement

当我运行此页面时,一切都显示正确,但是当我尝试测试各种错误消息时,我的按钮会将我重定向回我的登录页面,就好像所有内容都输入正确一样。它无法注册我包含的if块。下面是php(html运行正常,不包括在内)。

*旁注,几行被注释掉,因为我最初有PDO并且正在将它们更改为mysql,但这些不应该影响其他所有运行。我也让他们注释掉了如果事情确实有效,我没有在我的数据库中添加不必要的信息。

2 个答案:

答案 0 :(得分:4)

当然,PHP并没有跳过任何东西。它正在努力运行您的条件,但在您的代码中,影响插入的唯一条件是最后一个条件。

要使其按预期工作,您必须将所有ifs更改为elseif除第一个

答案 1 :(得分:0)

问题:您的错误可能已设置,但INSERT仅在$password == $password2执行时才会执行,如果它们都为空,则为真。

您需要通过执行else if

来指明替代路径
<?php
error_reporting (E_ALL);

$error = "";

if (isset($_POST['createAccount'])){
    $username = $_POST['username'];
    $password = $_POST['password'];
    $password2 = $_POST['password2'];
    $firstName = $_POST['firstName'];
    $lastName = $_POST['lastName'];
    $address = $_POST['address'];
    $city = $_POST['city'];
    $province = $_POST['province'];
    $postalCode = $_POST['postalCode'];

    if (!$username){
        $error = "<br><div><em>No username entered.</em></div>";
    }
    elseif (!$password || !$password2){
        $error = "<br><div><em>Missing password.</em></div>";
    }
    elseif (!$firstName || !$lastName){
        $error = "<br><div><em>Please enter first and last name.</em></div>";
    }
    elseif (!$address || !$city || !$province || !$postalCode){
        $error = "<br><div><em>Insufficient address provided. Please fill in all fields.</em></div>";
    }
    elseif ($password != $password2){
        $error = "<br><div><em>Passwords do not match.</em></div>";
    }       
    else{

        $conn = mysql_connect(<blocked out for privacy reasons>);
        $db = mysql_select_db("grocery", $conn);

        $account = mysql_query("SELECT * 
                                    FROM accounts 
                                    WHERE username = '$username'",
                                $conn);

        $rowExist = mysql_num_rows($account);

        if ($rowExist == 1){
            $error = "<br><div><em>Username already exists.</em></div>";
        }

        else {

            //$newAccount = ("INSERT INTO accounts (username, password, first_name, last_name, street, city, province, postal_code)
            //                  VALUES ('$username','$password','$firstName','$lastName','$address','$city','$province','$postal_code')");
            //$conn->exec($newAccount);

            header("location: GroceryLogin.php");
        }
        mysql_close($conn);
    }
}   

// I'm guessing here you do an echo $error;