尝试将表单值发送到数据库

时间:2018-07-29 20:25:06

标签: php mysql database forms mysqli

我在将表格值发送到mysql数据库时遇到了问题,我阅读了所有其他主题,我做了他们写的内容,但是我没有得到我想要的内容,请帮助我:(

        <?php
      $dbhost = "localhost";
      $dbuser = "root";
      $dbpass = "13838383";
      $dbname = "users";
      $connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
    ?>
    <?php
    include("../includes/functions.php");
    ?>
    <!DOCTYPE html>
    <html>
      <head>
        <link rel="stylesheet" href="../public/stylesheets/style.css" type="text/css">
        <title>Our WebPage</title>
      </head>
      <body>
        <center>
        <form action="input.php" method="post">
          <fieldset>
            <legend>Register</legend>
            <span>UserName: </span><br />
            <input type="text" name="username" placeholder="USERNAME"><br /><br />
            <span>PassWord: </span><br />
            <input type="text" name="lastname" placeholder="PASSWORD"><br /><br />
            <input type="button" name="submit" value="submit"><br /><br />
            <fieldset>
        </form>
        </center>
        <?php
        ?>
        <?php
          if (isset($_POST['submit'])) {
            $username = $_POST['username'];
            $password = $_POST['password'];
            $addUserQuery = "INSERT INTO users (username, password) VALUES ({$username}, {$password});";
            $added = mysqli_query($connection, $addUserQuery);
            if ($added) {
              echo '<br>Input data is successful';
            } else {
              echo '<br>Input data is not valid';
            }
          }
        ?>
      </body>
    </html>

我的问题是我不知道我该在表单标签的action属性中输入什么,谢谢帮助

1 个答案:

答案 0 :(得分:0)

简单地说,您的变量没有加引号,因此您的查询就变成了这种情况(如果有人提交了1337user作为用户名,P@ssw0rd作为密码):

INSERT INTO users (username, password) VALUES (1337user, P@ssw0rd);

应该在什么时候出现:

INSERT INTO users (username, password) VALUES ('1337user', 'P@ssw0rd');

改为绑定变量: How can I prevent SQL injection in PHP?

if (isset($_POST['submit'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $addUserQuery = mysqli_prepare($connection, "INSERT INTO users (username, password) VALUES (?, ?)");
    mysqli_stmt_bind_param($addUserQuery, "ss", $username, $password);
    $added = mysqli_stmt_execute($addUserQuery);
    if ($added) {
      echo '<br>Input data is successful';
    } else {
      echo '<br>Input data is not valid';
    }
}