首页 > 解决方案 > 即使php语句返回false,Ajax也会将数据插入数据库

问题描述

索引.php

<form action="../inc/q_camp.php" method="POST" class="modalForm">
        <h3>Campaign</h3><br>
        <label>Name</label><br>
        <input type="text" name="campName" required><br>
        <label>Customer</label><br>
        <select name="client" required>
          <option value="1">Abc</option>
        </select><br>
        <label>Start in</label><br>
        <input type="date" name="campStart" id="cStrt" required><br>
        <label>End in</label><br>
        <input type="date" name="campStop" required><br>
        <input type="button" name="toStore" value="Next">
    </form>

ajax.js

/*This function submit ".modalForm"*/
function submitForm1(){
    return $.ajax({
        type: "POST",
        url: "../inc/q_camp.php",
        data: $(".modalForm").serialize()
    });
}

/*When the button with name "toStore" is pressed, call submitForm1*/
$("input[name=toStore]").click(function(){
    submitForm1();
});

q_camp.php

/*Submit the campaign*/
if(!empty($_POST['campName']) || !empty($_POST['client']) || 
    !empty($_POST['campStart']) || !empty($_POST['campStop']))
{
    $sql = "INSERT INTO campaigns(cmp_name, customer_id, cmp_start, cmp_stop) VALUES (:cName,:cId,:cStr,:cStp)";
    $query = $db->prepare($sql);
    $query->bindParam('cName', $_POST['campName']);
    $query->bindParam('cId', $_POST['client']);
    $query->bindParam('cStr', $_POST['campStart']);
    $query->bindParam('cStp', $_POST['campStop']);
    $query->execute();
}else print_r("Failed");

即使不满足 php if 语句,ajax 函数也会在数据库中插入......如果我让“campName”输入为空,我会得到“失败”,但该行被插入到数据库中,如“cmp_id 1, cmp_name NOTHING, customer_id 1,cmp_start 00-00-0000,cmp_stop 00-00-0000”。

在数据库中,所有字段都设置为 NOT NULL。

我想了解即使不满足来自 PHP 的 if 语句,AJAX 如何访问 SQL 查询,即使列设置为空,如何插入行以及我做错了什么。

标签: phpajax

解决方案


推荐阅读