简体   繁体   English

我正在开发将信息提交到数据库的AJAX表单。 到达插入功能时记录错误

[英]I'm developing an AJAX form that submits information to a database. It's logging an error when it reaches the insert function

I've put together an ajax style form that has a simple animated validation through jQuery. 我整理了一个Ajax样式表单,该表单具有通过jQuery进行的简单动画验证。 When everything checks out, it posts the content to my database. 一切检查完后,它将内容发布到我的数据库中。 Or at least, that's the idea. 或至少是这个主意。 Right now it logs an error at the very end of the function rather than inserting the information. 现在,它在函数的最后记录了一个错误,而不是插入信息。

It consists of: 它包括:

  • db.php , connects to database db.php ,连接到数据库
  • scripts.js (+jQuery), form validation scripts.js (+ jQuery),表单验证
  • index.php , the form and such index.php ,形式等
  • insert.php , inserts post data into the database insert.php ,将发布数据插入数据库

db.php db.php中

<?$con = mysql_connect("localhost","db_name","db_pass");
    if (!$con){die('Could not connect: ' . mysql_error());}
?>

scripts.js scripts.js中

$(document).ready(function () {
    $("#submit").click(function (e) {
        e.preventDefault();

    // Tell console that it's started the validation
        console.log("Begin Validation");

    // Dump post data into variables
        var alert = false;
        var first = $("#firstname").val();
        var last = $("#lastname").val();
        var email = $("#email").val();
        var phone = $("#phone").val();
        var dropdown = $("#dropdown").val();

    // Check first name field 
        if (first.length === 0) {
            var alert = true;
            $("#firstname").addClass("error");
        } else {
            $("#firstname").removeClass("error");
        }

    // Check last name field
        if (last.length === 0) {
            var alert = true;
            $("#lastname").addClass("error");
        } else {
            $("#lastname").removeClass("error");
        }

    // Check email field
        if (email.length < 7 || email.indexOf("@") == "-1" || email.indexOf("@.") != -1 || email.indexOf("-.") != -1 || email.indexOf("_.") != -1 || email.indexOf("..") != -1 || email.indexOf("._") != -1 || email.indexOf(".-") != -1 || email.indexOf(".@") != -1 || email.indexOf("@-") != -1 || email.indexOf("@_") != -1 || email.indexOf("@") == -1 || email.indexOf(".") == -1) {
            var alert = true;
            $("#email").addClass("error");
        } else {
            $("#email").removeClass("error");
        }

    // Check phone field
        if (phone.length === 0) {
            var alert = true;
            $("#phone").addClass("error");
        } else {
            $("#phone").removeClass("error");
        }

    // Check dropdown field
        if ($("#dropdown").val() === 0) {
            var alert = true;
            $("#dropdown").addClass("error");
        } else {
            $("#dropdown").removeClass("error");
        }

    // If anything returned an error, display the alert dialog
        if (alert === true) {
            $(".formcheck").slideDown(500);
        }

    // If no issues were found, disable submit button and proceed to data insertion
        if (alert === false) {
            $(".formcheck").slideUp(500);
            $("#submit").attr({
                disabled: "true",
                value: "Sending Info..."
            });

            console.log("Finish validation, move on to insert.php");

        // Insert the data into the database via php file, echo success message to form
            $.post("insert.php", $("#form").serialize(), function (e) {
                console.log("Post data to insert.php");
                if (e == "sent") {
                    console.log("Hide submit button and display success message");
                    $("#submit").slideUp(500);
                    $(".formfail").slideUp(500);
                    console.log("remove submit and errors");
                    $(".formsuccess").slideDown(500);
                    console.log("message sent successfully");
                } else {
                    console.log("something went wrong");
                    $("#submit").removeAttr("disabled").attr("value", "Submit");
                }
            });
        }
    });
});

index.php 的index.php

<? include 'db.php'; ?>
<!doctype html>
  <head>
      <!-- meta info and such goes here -->

      <link rel='stylesheet' href='theme.css' type='text/css' media='all' />
      <script type='text/javascript' src='jquery.js'></script>
      <script type='text/javascript' src='scripts.js'></script>
  </head>
  <body>
    <form action='#submit' method='post' id='form'>
    <div class='formsuccess'>Your entry has been submitted; Thank you.</div>
    <div class='formerror'>There was a problem submitting the entry.</div>
    <div class='formcheck'>Please check the form, something's missing.</div>
    <div class='formfail'>There was a problem contacting the server.</div>

    <input type="text" name="firstname" id="firstname" tabindex="1" placeholder="First Name">
    <input type="text" name="lastname" id="lastname" tabindex="2" placeholder="Last Name">
    <input type="text" name="email" id="email" tabindex="3" placeholder="Email">
    <input style="display:none" id="email2" name="email2" type="text">
    <input type="text" name="phone" id="phone" tabindex="4" placeholder="Phone">

    <select name="dropdown" id="dropdown" tabindex="5">
      <option value="0">Please select an option...</option>
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option>
    </select>

    <input id="submit" name="submit" type="button" value="Submit"  tabindex="6"/>
  </body>
</html>

insert.php insert.php

<?$con = mysql_connect("localhost","db_name","db_pass");
    if (!$con){die('Could not connect: ' . mysql_error());}

mysql_select_db("db_name", $con);

//This bit makes the data input secure (preventing things like drop_tables, etc...)
function sanitize($input){
    switch(gettype($input)){
            case 'object':
            foreach($input as $key => $variable){
                            $input->$key = sanitize($variable);
                    }
            break;
            case 'array':
                    foreach($input as $key => $variable){
                            $input[$key] = sanitize($variable);
                    }
            break;
            case 'string':
                    //clean out extra sql queries
                    //remove poison null byte
                    //remove blank space at beginning and end of string
                    $input = mysql_real_escape_string(trim(htmlentities(str_replace(chr(0),'',$input),ENT_QUOTES)));
            break;
    }
    return $input;
}
//create an alias for "clean" version of our variable.
$post = sanitize($_POST);
//now use $post['firstname'] instead of $_POST['firstname'], $post has been cleaned.

//INSERT POST DATA INTO TABLES
$sql="INSERT INTO 'db_name'.'table_name' ('firstname', 'lastname', 'phone', 'email', 'dropdown')
    VALUES ('".$post['firstname']."','".$post['lastname']."','".$post['phone']."','".$post['email']."','".$post['dropdown']."')";

if (!mysql_query($sql,$con))
  {
    die('Error: ' . mysql_error());
  }

echo 'sent';

mysql_close($con);

?>

That's all of it (of course, I stripped out branded bits). 就这些了(当然,我去除了烙印的位)。 As it is now, it logs "something went wrong" 现在,它记录“出了点问题”

出问题了

Which means it passes the JavaScript validation and successfully reaches the last function. 这意味着它通过了JavaScript验证并成功到达了最后一个函数。 unfortunately it isn't able to insert the information into the database and defaults to the else statement, which doesn't return the "sent" message to the script file -- thus no success. 不幸的是,它无法将信息插入数据库,并且默认为else语句,该语句不会将“已发送”消息返回到脚本文件中-因此无法成功。

I've been tinkering with this thing for hours and can't figure out why it's failing. 我已经花了几个小时来修补这个东西,却不知道为什么它失败了。

You need to use backticks, not quotes for table/column names. 您需要使用反引号,而不是表/列名的引号。

$sql="INSERT INTO `db_name`.`table_name` (`firstname`, `lastname`, `phone`, `email`, `dropdown`)
    VALUES ('".$post['firstname']."','".$post['lastname']."','".$post['phone']."','".$post['email']."','".$post['dropdown']."')"

Or none, just: 或没有,只是:

$sql="INSERT INTO table_name (firstname, lastname, phone, email, dropdown)
    VALUES ('".$post['firstname']."','".$post['lastname']."','".$post['phone']."','".$post['email']."','".$post['dropdown']."')"

I also would trash your sanitize() function and all the mysql_* functions and revert to parametrized queries instead. 我也将废弃您的sanitize()函数和所有mysql_*函数,而是恢复为参数化查询。 Look into PDO , something like: 查看PDO ,类似:

$db = new PDO('mysql:dbname=db_name;host=127.0.0.1;charset=utf8', 'db_name', 'db_pass');

$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

$stmt = $db->prepare('INSERT INTO table (firstname, lastname, phone, email, dropdown) VALUES (:firstname, :lastname, :phone, :email, :dropdown)';
$stmt->execute(array('firstname' => $_POST['firstname'], 'lastname' => $_POST['lastname'],
'phone' => $_POST['phone'], 'email' => $_POST['email'], 'dropdown' => $_POST['dropdown']));

mysql_real_escape_string is not a good way to escape data instead you should use PDO, prepared statements. mysql_real_escape_string不是一种转义数据的好方法,而应该使用PDO,准备好的语句。 In PDO you do not have to escape data. 在PDO中,您不必转义数据。 PDO will take care of it. PDO会照顾好它。 Use bindParam to insert parameterized data in db. 使用bindParam将参数化数据插入db。

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

相关问题 尝试将数据插入数据库时​​出错。 简单的形式 - Error when trying to Inserting into data into the database. Simple form 我无法在数据库中插入数据。 我要去哪里错了? - I can't insert data in my database. Where I'm going wrong? 表单提交就像ajax无法正常工作一样 - Form submits like ajax's not working 有没有一种方法可以记录用户从MySQL数据库中提交表单的浏览器 - Is there a way of logging the browser a user submits a form from in MySQL database 我想从数据库中查看特定的用户信息。 但我收到这个错误 - I want to view a particular user information from database. But i recieve this error Ajax表单提交 - Ajax form submits 我无法将表单信息插入数据库中,但不断收到404错误 - I cannot insert my form information into my database I keep getting a 404 error 当我在数据库上执行 select 时,Ajax 请求将不起作用。 (拉拉维尔) - Ajax request won't work when I do a select on database. (Laravel) 我在从php文件中的应用程序接收注册信息时遇到麻烦,无法将该信息插入MSQL数据库中 - I'm having trouble receiving the registration information from the app in my php file to insert that information into the MSQL database Ajax表单提交在首次提交时返回错误,但在第二次单击时提交 - Ajax form submit returns error on first submit but submits on second click
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM