【问题标题】:PHP INSERT Prepared statement not inserting with ajaxPHP INSERT Prepared 语句未使用 ajax 插入
【发布时间】:2016-07-27 17:46:09
【问题描述】:

我正在尝试使用 ajax 和预准备语句形式的查询创建一个 INSERT 语句。我之前从未使用过 AJAX 和 PDO,所以请原谅我的无知。

就这样,我得到了alert(data); 错误,但弹出的警报只是说“错误|”。这是指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(isset($_POST['add'])) { 更改为您的变量,例如 $add_first$add_last$add_product 它不起作用,因为您没有 $_POST['add']
  • 所以这样做? if(isset($add_first, $add_last, $add_product) { ...}
  • 使用&amp;&amp; 代替,
  • 不过,我认为它甚至没有进入 php 文件。网络标签中没有显示任何内容。
  • if (!empty($add_first) &amp;&amp; !empty($add_last) &amp;&amp; !empty($add_product)) { 这样做...如果您确定所有值都应该始终具有值。如果 3 个中有空值,则不会插入

标签: javascript php jquery ajax pdo


【解决方案1】:

你最好先测试一下这些变量,这样就不会出现“未定义索引”的提示了。

而且由于您没有名为 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
}

【讨论】:

    【解决方案2】:
    • 使用if (!empty($add_first) &amp;&amp; !empty($add_last) &amp;&amp; !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.
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2021-02-11
      • 1970-01-01
      • 1970-01-01
      • 2014-01-05
      • 1970-01-01
      • 1970-01-01
      • 2011-06-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多