简体   繁体   English

使用 PHP 从 HTML 表单中获取 mySQL 数据库输入

[英]Taking mySQL database input from HTML form with PHP

I'm trying to take in data from a webpage with a HTML form and PHP to my mySQL Database.我正在尝试将带有 HTML 表单和 PHP 的网页中的数据接收到我的 mySQL 数据库中。 It connects just fine on both pages but I get an error when I try to submit from the form.它在两个页面上都连接得很好,但是当我尝试从表单提交时出现错误。 It will take in data if I just write it into the PHP myself and click submit, but it won't take it from the form so there must be something wrong there but I can't figure out what.如果我自己将数据写入 PHP 并单击提交,它将接收数据,但它不会从表单中获取数据,因此那里一定有问题,但我不知道是什么。 I've never used PHP with mySQL before so I'm not too sure how it all works.我以前从未在 mySQL 中使用过 PHP,所以我不太确定它是如何工作的。 Any help with an explanation of how it's working would be appreciated.任何解释它是如何工作的帮助将不胜感激。

Below is my test.html.php page where my form is and the testinsert.php page where I try to insert the data.下面是我的表单所在的 test.html.php 页面和我尝试插入数据的 testinsert.php 页面。

(Also, courseID is a foreign key in the 'test' table, so i need to make the courseID selectable from the options, i struggled with this and I don't know if this is where the issue lies. In the current code it is in a drop down menu, it shows the courseID's but there is a blank option in between each option eg the list of options will be - '4', 'blank', '5'... etc) (此外,courseID 是“test”表中的外键,因此我需要从选项中选择 courseID,我对此感到很挣扎,我不知道这是否是问题所在。在当前代码中位于下拉菜单中,它显示课程 ID,但每个选项之间有一个空白选项,例如选项列表将是 - '4'、'空白'、'5'...等)

<!DOCTYPE html>

<?php
include 'connect.php';
?>

<html lang="en">
<head>
    <link rel="stylesheet" type="text/css" href="style.css" />
    <meta name="viewport" content="width=1024, initial-scale=1.0, maximum-scale=1.0,user-       scalable=no"/>
</head>
    <title>Test Sign Up</title>
<body>

<header>
    <h1>Test Sign Up</h1>

</header>
        <div class="contactform">
            <form action="testinsert.php" method ="post">

                <label for="name">Name:</label>
                <input type="text" id="name" name="name" placeholder="Enter 
                your name here" required>

                <label for="testsentence">Test Sentence:</label>
                <input type="text" id="testsentence" name="testsentence" placeholder="Enter your sentence here" required>


                <label for="course">Course:</label>
                <select id="course" name="course">
                <?php

                $query = "SELECT CourseID FROM Course";

                $result = mysqli_query($conn, $query);


                while($row = mysqli_fetch_array($result)){

                    echo "<option>" . $row['CourseID'] . "<option>";

                }

                mysqli_close($conn);

                ?>
                </select>

            <button type="submit" name="submit">Submit</button>

            </form>                                    
        </div>
    <p></p>
    <a href="courses.html.php">View Courses</a>
    <p></p>
    <a href="index.html">Return to home page</a>
</body>    
</html>

Testinsert.php - Testinsert.php -

<?php
include 'connect.php';

$name = 'name';
$testsentence = 'testsentence';
$courseid = 'course';

$sql="INSERT INTO Test (Name, TestSentence, Course)
VALUES ('$name','$testsentence', '$courseid')";

if (mysqli_query($conn, $sql)) {
    echo "<p></p>New record added successfully";
    echo '<p></p><a href="index.html">Return to home page</a>';
} else {
    echo "<p></p>Error adding record";
    echo '<p></p><a href="index.html">Return to home page</a>';
}

mysql_close($conn);
?>

You are getting blank options AFTER each option with an expected value because you have failed to write a closing option tag.由于您未能编写结束选项标签,因此在每个具有预期值的选项之后,您将获得空白选项。 / needs to be written into the second option tag like this: /需要像这样写入第二个选项标签:

while ($row = mysqli_fetch_array($result)) {
    echo "<option>{$row['CourseID']}</option>";
}

The option tags still render even if you don't properly close them.即使您没有正确关闭选项标签,它们仍然会呈现。 In this case, the error presents itself by generating twice the desired tags.在这种情况下,错误会通过生成两倍所需的标签来呈现。

I recommend that you use MYSQLI_ASSOC as the second parameter of your mysqli_fetch_array call or more conveniently: mysqli_fetch_assoc我建议您使用MYSQLI_ASSOC作为mysqli_fetch_array调用的第二个参数或更方便: mysqli_fetch_assoc

In fact, because $result is iterable, you can write:事实上,因为$result是可迭代的,你可以这样写:

foreach ($result as $row) {
    echo "<option>{$row['CourseID']}</option>";
}

About using extract($_POST) ...关于使用extract($_POST) ...

I have never once found a good reason to use extract in one of my scripts.我从来没有找到在我的一个脚本中使用extract的充分理由。 Not once.不止一次。 Furthermore, the php manual has a specific Warning stating:此外,php 手册有一个特定的警告说明:

Warning Do not use extract() on untrusted data, like user input (eg $_GET, $_FILES).警告不要对不受信任的数据使用extract(),例如用户输入(例如$_GET、$_FILES)。

There are more warning down the page, but you effectly baked insecurity into your code by calling extract on user supplied data.页面下方有更多警告,但您通过对用户提供的数据调用extract ,有效地将不安全因素融入了代码中。 DON'T EVER DO THIS, THERE IS NO GOOD REASON TO DO IT.永远不要这样做,没有充分的理由这样做。

Here is a decent page that speaks about accessing submitted data: PHP Pass variable to next page这是一个关于访问提交数据的不错的页面: PHP Pass variable to next page

Specifically, this is how you access the expected superglobal data:具体来说,这是您访问预期超全局数据的方式:

$name = $_POST['name'];
$testsentence = $_POST['testsentence'];
$courseid = $_POST['course'];

You must never write unfiltered, unsanitized user supplied data directly into your mysql query, it leads to query instability at best and insecurity at worst.您绝不能将未经过滤、未经消毒的用户提供的数据直接写入您的 mysql 查询,这最多会导致查询不稳定,最坏会导致不安全。

You must use a prepared statement with placeholders and bound variables on your INSERT query.您必须在 INSERT 查询中使用带有占位符和绑定变量的准备好的语句。 There are thousands of examples of how to do this process on Stackoverflow, please research until it makes sense -- don't tell yourself that you'll do it layer.在 Stackoverflow 上有数以千计的关于如何执行此过程的示例,请研究直到它有意义为止——不要告诉自己你会分层进行。

Make sure you added extract($_POST) (or something similar) in your PHP code!确保您在 PHP 代码中添加了extract($_POST) (或类似的东西)!

You need to extract the parameters from your POST request before using them, otherwise your $name , $testsentence , and $courseid will be undefined.在使用它们之前,您需要从 POST 请求中提取参数,否则您的$name$testsentence$courseid将是未定义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM