PHP INSERT Prepared语句未使用ajax插入


PHP INSERT Prepared statement not inserting with ajax

我正试图使用ajax创建一个INSERT语句,并以准备好的语句形式创建查询。我以前从未将ajax与PDO一起使用过,所以请原谅我的无知。

按照这种方式,我得到了alert(data);错误,但弹出的警报只是说"error|"。这是指javascript不正确还是php文件?我相信这是javascript,因为我甚至没有让php文件显示在我的控制台网络选项卡中

我的AJAX有什么问题?

<form method="POST" id="pdo-add">
    <input name="first" id="pdo-add-first" placeholder="First Name">
    <input name="last" id="pdo-add-last" placeholder="Last Name">
    <input name="product" id="pdo-add-product" placeholder="Product">
    <input name="add" type="submit" value="Add">
</form>

AJAX

$(function() {
   $("#pdo-add").on("submit", function (event) {
    event.preventDefault();
    var add_first = $("#pdo-add-first").val();
    var add_last = $("#pdo-add-last").val();
    var add_product = $("#pdo-add-product").val();
    $.ajax({ 
        url: "pdoAddSend.php", 
        type: "POST",
        data: {
            "add_first": add_first,
            "add_last": add_last,
            "add_product": add_product
        },
        success: function (data) {
        //  console.log(data); // data object will return the response when status code is 200
            if (data == "Error!") {
                alert("Unable to insert product record!");
                alert(data);
            } else {
                //$("#newsletter-form")[0].reset();
                $('.announcement_success').html('Product Successfully Added!');
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            alert(textStatus + " | " + errorThrown);
            //console.log("error"); //otherwise error if status code is other than 200.
        }
    });
});
});

PHP

ini_set('display_errors', 1);
error_reporting(E_ALL);
$add_first = $_POST['add_first'];
$add_last = $_POST['add_last'];
$add_product = $_POST['add_product'];
try {
    $host = 'localhost';
    $name = '';
    $user = '';
    $password = '';
    $dbc = new PDO("mysql:host=$host;dbname=$name", $user, $password);
}catch(PDOException $e) {
    echo $e->getMessage();
}
//if(isset($_POST['add'])) {
if(isset($add_first && $add_last && $add_product) {
    $stmt = $dbc->prepare("INSERT INTO users (first, last, product) VALUES (:first,:last,:product)");
    $stmt->bindParam(':first', $add_first);
    $stmt->bindParam(':last', $add_last);
    $stmt->bindParam(':product', $add_product);
    $stmt->execute();
}
  • 使用if (!empty($add_first) && !empty($add_last) && !empty($add_product)) {检查空值
  • 使用数据库中的dataType json to return数组
  • ajax成功时动态插入输入

JS-

$.ajax({
    url: "pdoAddSend.php",
    type: "POST",
    data: {
        "add_first": add_first,
        "add_last": add_last,
        "add_product": add_product
    },
    dataType: "json",
    success: function(data) {
        for (var i = 0; i < data.length; i++) {
            var tr = $('<tr/>');
            tr.append("<td><input name='id' value=" + data[i].id + " readonly=''></td><td><input name='first' value=" + data[i].first + "></td><td><input name='last' value=" + data[i].last + "></td><td><input name='product' value=" + data[i].product + "></td><td><input name='save' type='submit' value='Save'></td><td><input name='delete' type='submit' value='Delete'></td>");
            $("#tableid").append(tr);
        }
        console.log(data); // data object will return the response when status code is 200
        if (data == "Error!") {
            alert("Unable to insert product record!");
            alert(data);
        } else {
            //$("#newsletter-form")[0].reset();
            $('.announcement_success').html('Product Successfully Added!');
        }
    },
    error: function(xhr, textStatus, errorThrown) {
        alert(textStatus + " | " + errorThrown);
        //console.log("error"); //otherwise error if status code is other than 200.
    }
});

您最好先测试这些变量,这样就不会出现"未定义索引"通知。

因为您没有一个名为add的POST变量,所以if(isset($_POST['add']))总是FALSE。

此处的代码:

if(isset($_POST['add_product']) && isset($_POST['add_last']) && isset($_POST['add_product'])) {
    $add_first = $_POST['add_first'];
    $add_last = $_POST['add_last'];
    $add_product = $_POST['add_product'];
//then your db execute code here
}