HTML if和else if语句错误

时间:2016-04-01 15:27:32

标签: php html mysql

我有一个带有两个按钮的html表单。一种是使用mysql查询登录,另一种是重定向到注册页面。登录按钮可以正常工作,但是注册按钮有点奇怪。它将运行它应该运行的函数,但它也返回有关if语句的登录按钮部分的错误。

HTML:

<html><head><title> Sign-In </title></head>
<body>

<h1> Login Form </h1>
<div id="Sign-In">
<form method="POST" action="connectivity.php">
Username: <input type='text' name='user'> <br><br>
Password: <input type='password' name='password'> <br><br>
<input type="submit" class="button" name="login_button" value="Login"> <br>
<input type="submit" class="button" name="register_button" value="Register">

</form>
</div>
</body>
</html>

PHP:

<?php
session_start();   //starting the session for user profile page
define('DB_HOST', 'localhost');
define('DB_NAME', 'project2');
define('DB_USER','root');
define('DB_PASSWORD','password');

if($_POST['login_button']){
    signin();
}
else if($_POST['register_button']){
    register();
}

function signin()
{
    $con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
    $db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());

    $ID = $_POST["user"];
    $Password = $_POST["password"];

    if(!empty($_POST['user']))   //checking the 'user' name which is from Sign-In.html, is it empty or have some text
    {
        $query =("SELECT *  FROM Customers where userName = '" .$ID. "' AND pass = '" .$Password. "';");

        $result = mysql_query($query, $con);
        if (mysql_num_rows($result) == 0)
        {
            echo "Invalid username or password.";
        }
        else
        {
            echo "Successfully logged in!";
        }
    }
    else
    {
        echo "Username field is empty!";
    }
}

function register()
{
    echo "please register";
}



?>

我得到的错误是:

Notice: Undefined index: login_button in C:\xampp\htdocs\project2\connectivity.php on line 8
please register

正如您所看到的,register()函数的回显工作正常,但我想它也在尝试signin()函数。根据点击的按钮,我只需要执行其中一个功能。提前谢谢!

2 个答案:

答案 0 :(得分:1)

当您执行if($_POST['login_button']){时,您需要检查该按钮是否存在于上一个表单中并且是通过帖子发送的,因为它位于表单内部。

如果要检查单击了哪个按钮,则必须执行此操作:

if(isset($_POST['login_button'])){
    signin();
}
else if(isset($_POST['register_button'])){
    register();
}

如果没有点击按钮,按钮就不会被设置。

答案 1 :(得分:1)

表单中不能有多个提交按钮。请参阅此说明:Multiple submit buttons in an HTML form