这有用吗?

时间:2016-06-20 17:44:36

标签: php html sql

<!DOCTYPE html>
<html>
<?php
$dbCon = mysqli_connect("localhost", "root", "", "test");

if (mysqli_connect_errno()) {
    echo "Failed to connect" .mysqli_connect_error();
}
if(isset($_POST['submit'])) {}





$sql = "INSERT INTO test (username, password) VALUES ('".$_POST['username']."','".$_POST['password']."')";

if (mysqli_query($dbCon, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($dbCon);
}


?>

<head>
    <title>Sign up page</title>
</head>
<body>



        <form method="post" action="signup.php">
            username: <input type="text" name="username" placeholder="username"><br>
            Password: <input type="password" name="password" placeholder="password"><br>
            <input type="submit" value="Create Account">
        </form>
</html>

我只想知道这是否会有效,因为我已经尝试过并且它似乎没有用。我想将用户输入的信息带到相应的字段中,并将该数据插入名为“test”的表中。但是它在变量$ sql的行上出现了错误。 我真的不知道我做错了什么,所以如果有人能清理的话会非常感激。

错误:

  

错误:注意:未定义的索引:第15行的C:\ wamp \ www \ Php-mySQL-login \ signup.php中的用户名

     

错误:注意:未定义的索引:第15行的C:\ wamp \ www \ Php-mySQL-login \ signup.php中的密码

2 个答案:

答案 0 :(得分:1)

在第if(isset($_POST['submit'])) {}行:您没有对if语句做任何事情。

您应该像这样设置:

<?php
if(isset($_POST['submit'])) { //If the user clicks the submit button.. process this code

    $dbCon = mysqli_connect("localhost", "root", "", "test");

    if (mysqli_connect_errno()) {
        echo "Failed to connect" .mysqli_connect_error();
    }

    $sql = "INSERT INTO test (username, password) VALUES ('".$_POST['username']."','".$_POST['password']."')";

    if (mysqli_query($dbCon, $sql)) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . mysqli_error($dbCon);
    }
}
?>
..HTML HERE..

我还在if语句中移动了数据库连接,因为除非用户点击提交按钮,否则没有理由连接到数据库。


修改

在评论中提及Danijel时,您应该使用mysqli_real_escape_string() mysqli prepared statements 来清理输入/防止SQL注入。

答案 1 :(得分:0)

PHP

<?php
$dbCon = mysqli_connect("localhost", "root", "", "test");

if (mysqli_connect_errno()) {
    echo "Failed to connect" .mysqli_connect_error();
}


if(isset($_POST['submit'])) {


$sql = "INSERT INTO test (username, password) VALUES ('".$_POST['username']."','".$_POST['password']."')";

    if (mysqli_query($dbCon, $sql)) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . mysqli_error($dbCon);
    }

}

?>

HTML

<form method="post" action="">
            username: <input type="text" name="username" placeholder="username"><br>
            Password: <input type="password" name="password" placeholder="password"><br>
            <input type="submit" name="submit" value="Create Account">
        </form>