简体   繁体   English

添加到SQL数据库的AJAX / HTML / PHP代码有什么问题?

[英]What's wrong with my AJAX/HTML/PHP code to add to my SQL database?

I'm trying to make a form that adds information to my MySQL database. 我正在尝试制作一种将信息添加到我的MySQL数据库的表单。 To do that, I have four scripts: 为此,我有四个脚本:

<html>
<head><title>Insert Data Into MySQL: jQuery + AJAX + PHP</title></head>
<body>

<form id="myForm" action="user_info.php" method="post">
User_id: <input type="text" name="user_id" /><br />
Hash : <input type="text" name="hash" /><br />
<button id="sub">Save</button>
</form>

<span id="result"></span>

<script src="jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="jcode.js" type="text/javascript"></script>
</body>
</html>

That's my main page, it mentions two other files, which are user_info.php and jcode.js (ignore the jQuery piece). 那是我的主页,其中提到了另外两个文件,分别是user_info.php和jcode.js(忽略jQuery部分)。 This is user_info.php 这是user_info.php

<?php
        include_once('db.php');

        $user_id = $_POST['user_id'];
        $hash = $_POST['hash'];

        if(mysqli_query("INSERT INTO _test('user_id, 'hash') VALUES('$user_id', '$hash')"))
          echo "Successfully Inserted";
        else
          echo "Insertion Failed";
?>

It points to db.php, so here's that: 它指向db.php,所以是这样的:

<?php
$con=mysqli_connect(" **taken out** ","root","password","test");
?> 

and finally, here's jcode.js: 最后是jcode.js:

$("#sub").click( function() {
 $.post( $("#myForm").attr("action"), 
         $("#myForm :input").serializeArray(), 
         function(info){ $("#result").html(info); 
   });
 clearInput();
});

$("#myForm").submit( function() {
  return false; 
});

function clearInput() {
    $("#myForm :input").each( function() {
       $(this).val('');
    });
}

For a while, it would say that the insertion was successful. 有一阵子,它会说插入成功。 But strangely,it would input blank rows in the database. 但是奇怪的是,它将在数据库中输入空白行。 I don't know what needs to be changed but now it just says "Insertion Failed". 我不知道需要更改什么,但是现在它只显示“插入失败”。 I'm fairly new to this technology, so I'm probably missing something obvious. 我对这项技术还很陌生,所以我可能缺少明显的东西。

It will be useful if you print for us the return of 如果您为我们打印退货单,这将很有用。

mysqli_error($con); 

after the line of 在行之后

echo "Insertion Failed";

From now, what can I say is that it's not an AJAX/jQuery problem (conceptual, at least) More information about mysqli_error function can be found here . 从现在开始,我可以说这不是AJAX / jQuery问题(至少是概念上的问题),有关mysqli_error函数的更多信息,请参见此处

And please, before getting it in production sanitize the user inputs as suggested here . 并且,请在将其投入生产之前,按照此处的建议对用户输入进行消毒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM