无法理解为什么这个 INSERT INTO sql 在 HTML 表格中不起作用

Can't figure why this INSERT INTO sql doesn't work in HTML Form

我在创建安全登录系统后尝试创建 "Create a Project" 表单时,很难在我的代码中找到麻烦制造者。

我感兴趣的是制作一个表格,在您登录后可以将项目插入我的数据库。就像我的网站都是关于众筹的,我希望用户能够创建项目名称以及他们项目的目标,首先。

我一直在使用 wikihow 指南来制作安全登录系统,并且它有效。 这是我的代码和来源:

<?php
include_once 'includes/register.inc.php';
include_once 'includes/functions.php';

$sql = "INSERT INTO projects (pname, pgoal) VALUES ('$pname','$pgoal')";

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Secure Login: Registration Form</title>
   <script type="text/JavaScript" src="js/sha512.js"></script>
   <script type="text/JavaScript" src="js/forms.js"></script>
    <link rel="stylesheet" href="styles/main.css" />
</head>
<body>
<!-- Registration form to be output if the POST variables are not
set or if the registration script caused an error. -->
<h1>Project Register</h1>
<?php
if (!empty($error_msg)) {
    echo $error_msg;
}
?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    Project Name: <input type='text' name='pname' id='pname' /><br>
    Project Goal: <input type="number" name="pgoal" id="pgoal" /><br>
    <input type="submit" value="Create" />
</form>

<p>Return to the <a href="index.php">login page</a>.</p>
</body>
</html>

来源: WikiHow - How to create a Secure..

您的代码存在以下问题:

这个:

$sql = "INSERT INTO projects (pname, pgoal) VALUES ('$pname','$pgoal')";

什么都不做

但是这个:

$pname = $_POST['pname'];
$pgoal = $_POST['pgoal'];

$sql = "INSERT INTO projects (pname, pgoal) VALUES ('$pname','$pgoal')";

$stmt = sqlsrv_query($connection, $query);

if ($stmt === false) {
    die(print_r(sqlsrv_errors(), true));
}

可以做点什么。

注意

我没有考虑 injection,我只是想让你看到你需要一个连接。

PLUS

有些评论是对的,你需要设置变量,而你只是在创建一个名为 $query

的变量

编辑

如果将 html 与 php

分开,您的代码会看起来更有条理

INSERT.PHP

<?php
include_once 'includes/register.inc.php';
include_once 'includes/functions.php';

   $sql = "INSERT INTO projects (pname, pgoal) VALUES ('$pname','$pgoal')";

   $plus what I added early

   ?>

HTML

  <!DOCTYPE html>
  <html>
  <head>
  <meta charset="UTF-8">
  <title>Secure Login: Registration Form</title>
  <script type="text/JavaScript" src="js/sha512.js"></script>
  <script type="text/JavaScript" src="js/forms.js"></script>
  <link rel="stylesheet" href="styles/main.css" />
  </head>
  <body>
  <!-- Registration form to be output if the POST variables are not
  set or if the registration script caused an error. -->
  <h1>Project Register</h1>

  <form action="insert.php" method="post">
  Project Name: <input type='text' name='pname' id='pname' /><br>
  Project Goal: <input type="number" name="pgoal" id="pgoal" /><br>
  <input type="submit" value="Create" />
  </form>

  <p>Return to the <a href="index.php">login page</a>.</p>
  </body>
 </html>