首页 > 解决方案 > PHP SQL 检查表单输入是否存在于其他表中,然后继续

问题描述

我正在编写一个表单,我希望代码检查参与者想要参加活动的插入“日期”是否与我的活动表中的“日期”匹配。目前(即使表单输入中的“日期”与事件表上的任何日期都不匹配)用户可以注册任何日期而不会收到验证错误。

在 html 表单“register.html”上,我有:

    <form action="register.php" method="post">
      <div class="form-group">
        <label for="date"> Date of attendence </label>
        <input type="date" class="form-control" id="date" name="date"/>
      </div>
      <input type="submit" class="btn btn-primary" />
    </form>

在“register.php”我有:

    <?php
        $date = $_POST['date'];

        $conn = new mysqli('localhost','root','','skay');
        if($conn->connect_error){
            echo "$conn->connect_error";
            die("Connection Failed : ". $conn->connect_error);
        } else {
    
            $date_check_query = "SELECT COUNT * FROM events WHERE date='$date'";
            $number_of_matches = mysqli_query($conn, $date_check_query);

            if ($number_of_matches = 0) {
                array_push($errors, "No planned events on this day");
            } else {
                $stmt = $conn->prepare("INSERT INTO registrations(date) values(?)");
                $stmt->bind_param("sssssi", $date); //there are other 5 other values aswell
                $execval = $stmt->execute();
                echo $execval;
                echo "Registration successfully...";
                $stmt->close();
                $conn->close();
            }
        }       
    ?>

格兹博

标签: phpsqlvalidation

解决方案


仔细检查您的代码,尤其是这里

if ($number_of_matches = 0) {

应该

if ($number_of_matches == 0) {

这不在您的问题范围内,但最好考虑 SQL 注入攻击并重新编写以下代码行:

$date_check_query = "SELECT COUNT * FROM events WHERE date='$date'";

推荐阅读