Php I';我正在开发一个AJAX表单,将信息提交到数据库。它';s在到达插入函数时记录错误

Php I';我正在开发一个AJAX表单,将信息提交到数据库。它';s在到达插入函数时记录错误,php,jquery,mysql,ajax,post,Php,Jquery,Mysql,Ajax,Post,我制作了一个ajax样式的表单,它通过jQuery进行了简单的动画验证。当所有内容都签出时,它会将内容发布到我的数据库中。或者至少,这是一个想法。现在,它在函数的最后记录一个错误,而不是插入信息 它包括: db.php,连接到数据库 scripts.js(+jQuery),表单验证 index.php、表单等 insert.php,将post数据插入数据库 db.php <?$con = mysql_connect("localhost","db_name","db_pass");

我制作了一个ajax样式的表单,它通过jQuery进行了简单的动画验证。当所有内容都签出时,它会将内容发布到我的数据库中。或者至少,这是一个想法。现在,它在函数的最后记录一个错误,而不是插入信息

它包括:

  • db.php
    ,连接到数据库
  • scripts.js
    (+jQuery),表单验证
  • index.php
    、表单等
  • insert.php
    ,将post数据插入数据库
db.php

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

?>

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");
                }
            });
        }
    });
});
$(文档).ready(函数(){
$(“#提交”)。单击(功能(e){
e、 预防默认值();
//告诉控制台已启动验证
日志(“开始验证”);
//将post数据转储到变量中
var警报=错误;
var first=$(“#firstname”).val();
var last=$(“#lastname”).val();
var email=$(“#email”).val();
var phone=$(“#phone”).val();
var dropdown=$(“#dropdown”).val();
//检查名字字段
if(first.length==0){
var alert=真;
$(“#firstname”).addClass(“错误”);
}否则{
$(“#firstname”).removeClass(“错误”);
}
//检查姓氏字段
如果(last.length==0){
var alert=真;
$(“#lastname”).addClass(“错误”);
}否则{
$(“#lastname”).removeClass(“错误”);
}
//检查电子邮件字段
若(email.长度<7|;;10.长度<7|;;10.dendxof(以下简称)的电子邮件长度<7|;10.dendxof(电子邮件长度<7124尺寸)的电子邮件长度<7|;电子邮件.电子邮件索引索引of(以下简称)的(((“,)==“,,!=)10 10-1|电子邮件.索引of(以下以下简称(((((“-)))的)的)长度<10 10)的)的)电子邮件.无损无损若若若(((((((,,,,,,,,))的)的)的)10 10 10)的)电子邮件.电子邮件.无损xof(((((,,,,,,,,,,,,,,,,,,,,,)10)的)的)的)对对对)的)电子邮件.索引of((((((((((,))))email.indexOf(“@”!=-1 | | email.indexOf(“@”)=-1 | | email.indexOf(“.”=-1){
var alert=真;
$(“#email”).addClass(“错误”);
}否则{
$(“#email”).removeClass(“错误”);
}
//检查电话字段
如果(phone.length==0){
var alert=真;
$(“#电话”).addClass(“错误”);
}否则{
$(“#phone”).removeClass(“错误”);
}
//检查下拉字段
if($(“#下拉列表”).val()==0){
var alert=真;
$(“#下拉列表”).addClass(“错误”);
}否则{
$(“#下拉列表”).removeClass(“错误”);
}
//如果有任何内容返回错误,请显示警报对话框
如果(警报===真){
$(“.formcheck”)。向下滑动(500);
}
//如果未发现任何问题,请禁用“提交”按钮并继续数据插入
如果(警报===错误){
$(“.formcheck”).slideUp(500);
$(“#提交”).attr({
禁用:“真”,
值:“正在发送信息…”
});
log(“完成验证,转到insert.php”);
//通过php文件将数据插入数据库,将成功消息回送到表单
$.post(“insert.php”,$(“#form”).serialize(),函数(e){
log(“将数据发布到insert.php”);
如果(e==“已发送”){
console.log(“隐藏提交按钮并显示成功消息”);
$(“#提交”)。幻灯片(500);
$(“.formfail”).slideUp(500);
日志(“删除提交和错误”);
$(“.formsuccess”)。向下滑动(500);
console.log(“消息发送成功”);
}否则{
log(“出了问题”);
$(“#提交”).removeAttr(“禁用”).attr(“值”、“提交”);
}
});
}
});
});
index.php

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

?>

您的参赛作品已提交;非常感谢。
提交条目时出现问题。
请检查一下这张表,少了一些东西。
联系服务器时出现问题。
请选择一个选项。。。
沃尔沃汽车
萨博
梅赛德斯
奥迪
insert.php

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

?>

仅此而已(当然,我去掉了品牌部分)。现在,它记录了“出了问题”

这意味着它通过了JavaScript验证并成功地到达了最后一个函数。不幸的是,它无法将信息插入数据库,默认为else语句,它不会将“sent”消息返回到脚本文件,因此没有成功


我已经修补这个东西好几个小时了,不知道为什么它会失败。

您需要使用反勾号,而不是表/列名的引号

$sql="INSERT INTO `db_name`.`table_name` (`firstname`, `lastname`, `phone`, `email`, `dropdown`)
    VALUES ('".$post['firstname']."','".$post['lastname']."','".$post['phone']."','".$post['email']."','".$post['dropdown']."')"
或者没有,只是:

$sql="INSERT INTO table_name (firstname, lastname, phone, email, dropdown)
    VALUES ('".$post['firstname']."','".$post['lastname']."','".$post['phone']."','".$post['email']."','".$post['dropdown']."')"
我还将丢弃你的
sanitize()
函数和所有的
mysql.*
函数,转而返回参数化查询。看看,比如:

$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不是一种很好的转义数据的方法,相反,您应该使用PDO、准备好的语句。在PDO中,您不必转义数据。PDO会处理的。使用bindParam在数据库中插入参数化数据。

您是否尝试过在ajax成功函数中提醒您将得到什么?例如,在这一行之后:
if(e==“sent”){
add:
alert(e)
并告诉我们您看到了什么。
console.log('Something gours:'+e)
。还不如输出出错的内容,而不是在黑暗中四处游荡。在向insert.php摆姿势后查看服务器响应。它可能包含mysql_error()的输出函数。或者您的响应中有其他字符、换行符、空格,而不仅仅是
sent
。很可能是
e
co