无法通过 PHP 绑定和准备语句将表单数据添加到数据库中

问题描述 投票:0回答:0

我一直在尝试通过 php 将我的表单数据插入到我的数据库中,我已经尝试了几个小时,但它对我一点用处都没有。

所以我的网页应该通过表单将用户注册到网站,但不幸的是我一直无法这样做。我已经通过 MySqlWorkbench 检查了我与数据库服务器的连接,连接也完全正常。

我遇到的问题是,尽管网站说我已经成功添加了用户,但它并没有真正用必要的记录更新数据库,我完全不知道问题是什么。

所以我有 2 个文件 - 一个用于注册表,另一个用于处理它。

报名表

<head>
        <title>Register</title>
        <!-- title at top of tab -->
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet"
        href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
        integrity=x
        "sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
        crossorigin="anonymous">
        <link rel="stylesheet" href="css/main.css">
        <!--jQuery-->
        <script defer
            src="https://code.jquery.com/jquery-3.4.1.min.js"
            integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
            crossorigin="anonymous">
        </script>
        
        <!-- Custom JS -->
        <script defer src="js/main.js"></script>
            <!--Bootstrap JS-->
            <script defer
            src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"
            integrity="sha384-6khuMg9gaYr5AxOqhkVIODVIvm9ynTT5J4V1cfthmT+emCG6yVmEZsRHdxlotUnm"
            crossorigin="anonymous">
        </script>
        
</head>

<body id="login_body" style= "background-image:url('/images/login_bg.jpg')">
    <?php
    include "nav.inc.php";
    ?>
    
    <main class="container">

<section class="background-radial-gradient overflow-hidden">
  
  <div class="container px-4 py-5 px-sm-5 text-center text-lg-start my-5">
    
    <div class="row gx-lg-5 align-items-center mb-5">
        

      <div class="col-lg-6 mb-5 mb-md-0 position-relative ">
          <h1>Register</h1>
          
        <!-- make the box for the form  -->  
        <div class="card bg-glass ">
            
           
          <div class="card-body px-1 py-5 px-sm-5">
            <form action="process_register.php" method="post">
              <!-- 2 column grid layout with text inputs for the first and last names -->
              
                  
                <div class="col-sm-12 mb-6">
                  <div class="form-outline form-floating mb-4">
                    <label for ="fname">First name</label>
                    <input type="text" aria-label="First Name" class="form-control" id="fname" name="fname">
                  </div>
                </div>
              
              
                <div class="col-sm-12 mb-6"> <!-- control space take out of 12 slots in screen and spacing-->
                  <div class="form-outline form-floating mb-4">
                      <label for = "lname">Last name</label>
                      <input type="text" aria-label="last name" class="form-control" required type="text" id="lname" name="lname">
                  </div>
                </div>
              

              <!-- Email input -->
              <div class="col-sm-12 mb-6"> <!-- control space take out of 12 slots in screen and spacing-->
                <div class="form-outline form-floating mb-4">
                        <label for="email">Email address</label>
                        <input type="email" aria-label="email" class="form-control" required type="email" id="email" name="email">
              </div>
                  
            <div class="col-sm-12 mb-6">  
            <div class="form-outline form-floating mb-4">
                  <label for ="phone">Phone Number</label> 
                   <input type="text" aria-label="Phone Number" class="form-control" required pattern= "^[89]\d{7}$" id="phone" name="phone"
                          oninvalid="this.setCustomValidity('Please enter a 8-digit Singapore number starting with 8 or 9 ')"
                          oninput="setCustomValidity('')"/>
                  
                  <!-- regex phone number must start with 8 and 9 and at most 8 digits total -->
            </div>
            </div>


              <!-- Password input -->
              <div class="form-outline form-floating mb-4">
                  <label for ="pwd">Password</label>
                   <input type="password" aria-label="Password" class="form-control" id="pwd" name="pwd">
                </div>
              
            
            <div class="form-outline form-floating mb-4">
                  <label for ="pwd_confirm">Confirm Password</label>
                   <input type="password" aria-label="Password" class="form-control" id="pwd_confirm" name="pwd_confirm">
            </div>

            <div class="form-check d-flex justify-content-center mb-4">
                <label>
                    <input type="checkbox" required name="agree">
                    Agree to terms and conditions.
                </label>
            </div>
              
            <div class="form-group"> 
               <button class="btn btn-dark" type="submit" >Register</button>
            </div>


            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

</body>

流程注册表格(process_register.php)

<!--DEH YOU AT 6.3 -->
<!DOCTYPE html>
<!--
Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
Click nbfs://nbhost/SystemFileSystem/Templates/Other/html.html to edit this template
-->

<html lang="en">

<head>
        <title>Process Register</title>
        <!-- title at top of tab -->
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet"
        href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
        integrity=
        "sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
        crossorigin="anonymous">
        <link rel="stylesheet" href="css/main.css">
        <!--jQuery-->
        <script defer
            src="https://code.jquery.com/jquery-3.4.1.min.js"
            integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
            crossorigin="anonymous">
        </script>
        <!-- Custom JS -->
        <script defer src="js/main.js"></script>
            <!--Bootstrap JS-->
            <script defer
            src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"
            integrity="sha384-6khuMg9gaYr5AxOqhkVIODVIvm9ynTT5J4V1cfthmT+emCG6yVmEZsRHdxlotUnm"
            crossorigin="anonymous">
        </script>
</head>

<body>
<?php
include "nav.inc.php";
$fname = $lname = $email = $phone = $errorMsg = "";
$success = true;
$hashed_pass="";
$success = true;

    if (empty($_POST["lname"]))
    {
        $errorMsg .= "Last Name is required.<br>";
        $success = false;
    }
    if (empty($_POST["email"]))
    {
        $errorMsg .= "Email is required.<br>";
        $success = false;
    }
    
    if (empty($_POST["phone"]))
    {
        $errorMsg .= "Phone is required.<br>";
        $success = false;
    }
    
    if (empty($_POST["pwd"]))
    {
        $errorMsg .= "Password is required.<br>";
        $success = false;
    }

    if (empty($_POST["pwd_confirm"]))
    {
        $errorMsg .= "Confirm Password is required.<br>";
        $success = false;
    }
    else
    {
    $fname = sanitize_input($_POST["fname"]);
    $lname = sanitize_input($_POST["lname"]);
    $email = sanitize_input($_POST["email"]);
    $phone = sanitize_input($_POST["phone"]);
    // Additional check to make sure e-mail address is well formed
    }
    if (!filter_var($email, FILTER_VALIDATE_EMAIL))
    {
    $errorMsg .= "Invalid email format.<br>";
    $success = false;
    }
    $password = $_POST["pwd"];
    $password_confirm = $_POST["pwd_confirm"];
    if($password != $password_confirm)
    {
    $errorMsg .= "Passwords do not match.<br>";
    $success = false;
    }
    else
    {
    // Hash password before storing in database
    $hashed_pass = password_hash($password, PASSWORD_DEFAULT);
    }

    if ($success)
    {
        // Insert data into database
        // ...
        echo "<div class='jumbotron'>"
        ."<h2 class>Your registration is successful, </h2>";
        echo  "<h3>Thank you for signing up," .$_POST["fname"]." " .$_POST["lname"] ."</h3>";
        echo '</h1>';
        saveMemberToDB($fname, $lname, $email, $phone, $hashed_pass);
    }
    else
    {
        echo "<div class='jumbotron'>"
        . "<h1 class='display-4'>Oops!</h1>";
        echo "<h2>The following input errors were detected:</h2>";
        echo "<p>" . $errorMsg . "</p>";
        echo "</div>";
    }

    // Sanitize user input to prevent SQL injection attacks
    function sanitize_input($data)
    {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }

?>

<?php
    /*
    * Helper function to write the member data to the DB
    */
    function saveMemberToDB($fname, $lname, $phone, $email, $hashed_pass)
    {
    // Create database connection.
    $config = parse_ini_file('../../private/db-config.ini');
    $conn = new mysqli($config['servername'], $config['username'],
    $config['password'], $config['dbname']);
    // Check connection
    if ($conn->connect_error)
    {
    $errorMsg = "Connection failed: " . $conn->connect_error;
    $success = false;
    }
    else
    {
    // Prepare the statement:
    $stmt = $conn->prepare("INSERT INTO members_info (fname, lname,
    email, phone, password) VALUES (?, ?, ?, ?, ?);");
    // Bind & execute the query statement:
    $stmt->bind_param("sssis", $fname, $lname, $email, $phone, $hashed_pass);
    if (!$stmt->execute())
    {
    $errorMsg = "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    $success = false;
    }
    $stmt->close();
    }
    $conn->close();
    }
?>
    
</body>
</html> 
php html mysql forms registration
© www.soinside.com 2019 - 2024. All rights reserved.