从POST获取表单数据并插入到mysqli数据库

Getting form data from POST and inserting to mysqli database

提问人:Sarah Browning 提问时间:10/19/2021 最后编辑:Sarah Browning 更新时间:10/19/2021 访问量:81

问:

在学习PHP和我最近的作业中,我必须创建一个HTML表单,使用PHP进行错误检查,使用mysqli将数据插入数据库,然后检索值并将它们显示在表格中。即使我没有 100% 工作,我也上交了作业,但我只是想在等待导师的反馈时找出我哪里出了问题。我已经检查了几个类似的线程,但到目前为止,提供的解决方案似乎都不适合我。

到目前为止,我的表单可以正常工作,它似乎可以很好地重定向并连接到数据库。它还检索已存储在数据库中的数据,并将其显示在表中。但是我一辈子似乎都无法让它实际写入通过POST提交的表单数据。 无论在表单上输入或未输入哪些数据,当单击提交按钮时,它都会将空白行写入我的数据库,这应该通过我的错误检查来防止。因此,此外,这是我的表单代码:

<?php
    include ("dbinfo.php");
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL & ~E_WARNING);

    //declare variables
    $errors = 0;

    //if form is submitted
    if ( isset($_POST['submit']) ) {

        //store submitted values
        $title = $_POST['title'];
        $firstName = $_POST['firstName'];
        $lastName = $_POST['lastName'];
        $street = $_POST['street'];
        $city = $_POST['city'];
        $province = $_POST['province'];
        $postal = $_POST['postal'];
        $country = $_POST['country'];
        $phone = $_POST['phone'];
        $email = $_POST['email'];
        $email = filter_var($email, FILTER_SANITIZE_EMAIL);
        $newsletter = $_POST['newsletter'];

        //error checking routine
        if ( !isset($_POST[$title]) || empty($_POST[$title]) ) $errors = 1;
        if ( !isset($_POST[$firstName]) || empty($_POST[$firstName]) ) $errors = 2;
        if ( !isset($_POST[$lastName]) || empty($_POST[$lastName]) ) $errors = 3;
        if ( !isset($_POST[$street]) || empty($_POST[$street]) ) $errors = 4;
        if ( !isset($_POST[$city]) || empty($_POST[$city]) ) $errors = 5;
        if ( !isset($_POST[$province]) || empty($_POST[$province]) ) $errors = 6;
        if ( !isset($_POST[$postal]) || empty($_POST[$postal]) ) $errors = 7;
        if ( !isset($_POST[$country]) || empty($_POST[$country]) ) $errors = 8;
        if ( !isset($_POST[$phone]) || empty($_POST[$phone]) ) $errors = 9;
        if ( !filter_var($email, FILTER_VALIDATE_EMAIL) === false ) $errors = 10;
        if ( !isset($_POST[$email]) || empty($_POST[$email]) ) $errors = 11;
    }

    //if error flag is still 0
    if ( $errors == 0 ) {
    
?>
<!-- display the form -->
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Form</title>
    </head>
    <body>
        <!-- if errors exist, display error message(s -->
        <p>
            <strong>Instructions:</strong> To complete your registration, please fill out the following form.
            <?php if ($errors > 0) echo "<p><font color=red><strong>Please ensure all required fields are filled.</strong></font></p>"; ?>
        </p>
        <form action="" method="POST" enctype="multipart/form-data">
            <label for="title" >Title</label>
            <select name="title">
                <option value="" <?php if (isset($title) && $title =="") echo "selected";?>></option>
                <option value="Mr" <?php if (isset($title) && $title == "Mr") echo "selected";?>>Mr</option>
                <option value="Mrs" <?php if (isset($title) && $title == "Mrs") echo "selected";?>>Mrs</option>
                <option value="Ms" <?php if (isset($title) && $title =="Ms") echo "selected";?>>Ms</option>
                <option value="Dr" <?php if (isset($title) && $title =="Dr") echo "selected";?>>Dr</option>
            </select>
            <?php if ( $errors > 0 && empty($title) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
            <br />
            <label for="firstName">First Name: </label>
            <input type="text" name="firstName" placeholder="Jane" value="<?php echo isset($_POST["firstName"]) ? $_POST["firstName"] : ''; ?>">
            <?php if ( $errors > 0 && empty($firstName) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
            <br />
            <label for="">Last Name: </label>
            <input type="text" name="lastName" placeholder="Doe" value="<?php echo isset($_POST["lastName"]) ? $_POST["lastName"] : ''; ?>">
            <?php if ( $errors > 0 && empty($lastName) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
            <br />
            <label for="">Street Address: </label>
            <input type="text" name="street" placeholder="123 ABC Drive" value="<?php echo isset($_POST["street"]) ? $_POST["street"] : ''; ?>">
            <?php if ( $errors > 0 && empty($street) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
            <br />
            <label for="">City: </label>
            <input type="text" name="city" placeholder="Anytown" value="<?php echo isset($_POST["city"]) ? $_POST["city"] : ''; ?>">
            <?php if ( $errors > 0 && empty($city) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
            <br />
            <label for="">Province: </label>
            <input type="text" name="province" placeholder="Nova Scotia" value="<?php echo isset($_POST["province"]) ? $_POST["province"] : ''; ?>">
            <?php if ( $errors > 0 && empty($province) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
            <br />
            <label for="">Postal Code:</label>
            <input type="text" name="postal" placeholder="A1A 1A1" value="<?php echo isset($_POST["postal"]) ? $_POST["postal"] : ''; ?>">
            <?php if ( $errors > 0 && empty($postal) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
            <br />
            <label for="country">Country: </label>
            <select name="country">
                <option value="" <?php if ( isset($country) && $country == "" ) echo "selected";?>></option>
                <option value="canada" <?php if (isset($country) && $country == "canada") echo "selected";?>>Canada</option>
                <option value="usa" <?php if (isset($country) && $country == "usa") echo "selected";?>>USA</option>
            </select>
            <?php if ( $errors > 0 && empty($country) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
            <br />
            <label for="phone">Phone Number: </label>
            <input type="text" name="phone" placeholder="555-555-5555" value="<?php echo isset($_POST["phone"]) ? $_POST["phone"] : ''; ?>">
            <?php if ( $errors > 0 && empty($phone) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
            <br />
            <label for="email">Email Address: </label>
            <input type="text" name="email" placeholder="[email protected]" value="<?php echo isset($_POST["email"]) ? $_POST["email"] : ''; ?>">
            <?php if ( $errors > 0 && empty($email) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
            <br />
            <label for="newsletter">Subscribe to our newsletter? </label>
            <input type="checkbox" name="newsletter" value="1">
            <br /><br />
            <input name="submit" type="submit" value="submit">
        </form>
    </body>
</html>

<?php 
} else {
//redirect to database
    header("Location: regdatabase.php");
    exit;
}

我的 dbinfo 文件只包含 $db_host、$db_user、$db_pass 和 $db_name。这是regdatabase.php的代码。

<?php
    include ("dbinfo.php");
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);

    //establish a DB connection to a specific database
    $conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);

    //check for valid connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }
    echo "Connected successfully. <br />";

    //prepare and bind
    $sql = "INSERT INTO registered_users (title, firstName, lastName, street, city, province, postal, country,  phone, email, newsletter)
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ssssssssssi", $_REQUEST['title'], $_REQUEST['firstName'], $_REQUEST['lastName'], $_REQUEST['street'], $_REQUEST['city'], $_REQUEST['province'],
                        $_REQUEST['postal'], $_REQUEST['country'], $_REQUEST['phone'], $_REQUEST['email'], $_REQUEST['newsletter']);
    $stmt->execute();
    $stmt->close();

    //retrieve values and display in table
    $sql = "SELECT * FROM registered_users";
    $results = mysqli_query($conn, $sql);
              
    if ($results->num_rows > 0) {
        echo "Data stored in database successfully.<br /><br />
          <table><tr>
          <th>User ID</th>
          <th>Title</th>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Street Address</th>
          <th>City</th>
          <th>Province</th>
          <th>Postal Code</th>
          <th>Country</th>
          <th>Phone Number</th>
          <th>Email Address</th>
          <th>Newsletter Sub</th>
          </tr>";
        while($row = mysqli_fetch_assoc($results)) {
            echo "<tr><td>" . $row["user_id"]. "</td>" . 
                 "<td>" . $row["title"]. "</td>" . 
                 "<td>" . $row["firstName"]. "</td>" . 
                 "<td>" . $row["lastName"]. "</td>" . 
                 "<td>" . $row["street"]. "</td>" . 
                 "<td>" . $row["city"]. "</td>" . 
                 "<td>" . $row["province"]. "</td>" . 
                 "<td>" . $row["postal"]. "</td>" . 
                 "<td>" . $row["country"]. "</td>" . 
                 "<td>" . $row["phone"]. "</td>" . 
                 "<td>" . $row["email"]. "</td>" . 
                 "<td>" . $row["newsletter"]. "</td></tr>";
        }
        echo "</table>";        
    } else {
        echo "There are 0 results.";
    }

    mysqli_close($conn);
?>

var_dump显示我的所有变量都是 NULL。空白记录正在数据库中记录。我还以以下格式重写了我的绑定语句,但也没有运气。

$title = $_POST['title'];
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$street = $_POST['street'];
$city = $_POST['city'];
$province = $_POST['province'];
$postal = $_POST['postal'];
$country = $_POST['country'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$newsletter = $_POST['newsletter'];

$stmt->bind_param("ssssssssssi", $title, $firstName, $lastName, $street, $province, $postal, $country, $phone, $email, $newsletter);

如果我像这样显式地编写和声明值,它们会正确地写入数据库,这似乎表明我准备好的语句工作正常。

$title = "Ms";
$firstName = "Jane";
$lastName = "Doe";
$street = "123 ABC Lane";
$city = "AnyTown";
$province = "Nova Scotia";
$postal = "A1A 1A1";
$country = "Canada";
$phone = "555-555-5555";
$email = "[email protected]";
$newsletter = 1;

$stmt->bind_param("ssssssssssi", $title, $firstName, $lastName, $street, $province, $postal, $country, $phone, $email, $newsletter);

我将非常感谢任何帮助来诊断为什么除了通过 POST 获取值之外一切似乎都有效。也愿意接受任何关于为什么我的错误检查在提交到数据库时似乎被跳过的提示。提前致谢!

php 表单 发布 mysqli prepared-statement

评论

0赞 ADyson 10/19/2021
所以,你展示的那段代码就是文件,对吗?它不是 100% 清楚的,如果您可以编辑问题以标记代码片段以说明它们来自哪个文件,那将会很有帮助。谢谢。regdatabase.php
0赞 ADyson 10/19/2021
无论如何,如果我的假设是正确的,那么你编写的任何错误检查代码都不会被使用,因为表单直接回发给regdatabase.php,它不包含任何错误检查代码 - 它只是尝试将表单数据中提交(或未提交)的任何内容直接写入数据库。这。。。。您第一页的位永远不会被使用,因为表单数据永远不会发送到那里。if ( isset($_POST['submit']) ) {
0赞 ADyson 10/19/2021
但这并不能解释为什么如果您确实提交了一些数据,它仍然会将空白信息保存到数据库中 - 据我所知,根据您显示的代码,这不应该发生。
0赞 Sarah Browning 10/19/2021
@ADyson 更新了代码以指示代码段的来源。你是对的,第二部分是regdatabase.php。至于重定向到regdatabase的动作,很好。我很早就把它放在那里,但忘记删除它,让页面直接发布回自己。但是,现在我似乎根本没有将任何内容写入数据库。
0赞 ADyson 10/19/2021
感谢您的更新。我注意到您现在已将表单的“action”方法更改为“”。这应该启用错误检查,但它会停止提交表单数据 - 这部分:不会如您所愿。重定向标头告诉浏览器向服务器发起新请求,这也是一个 GET 请求,而不是 POST。因此,由于它是新的,因此它不会包含您刚刚提交的任何表单数据。相反,您确实需要将数据库编写代码放入函数中,然后从该位置调用它。else { //redirect to database header("Location: regdatabase.php"); exit; }

答: 暂无答案