不能在数据库中插入自动填充字段


Can't insert into database an autofill fields?

这是我第一次在这里问,我一直试图在其他问题中寻找类似的东西,但找不到。

我有一个邮政编码线(文本框)和状态线(文本框)的形式,现在,通过输入有效的美国邮政编码,javascript会自动填充状态框。表格本身有点长。我只展示我编辑过的相关代码,它以前是一个选择菜单(一切都工作得很好-数据被输入数据库),我改变了它,所以不需要选择。

也有css文件,但这是无关紧要的(设计不是问题)

所以,这是我的html代码:
<html>
<head>some content here</head>
<body>
<form method="post" action="process.php">
<div class="title"><h2>my form title</h2></div><br>
<div align="center" class="element-name">
                             </span>
<span align="center" id="zipbox" class="nameFirst">
<input type="text" class="medium" pattern="[0-9]*" name="col2" id="col2" maxlength="5" placeholder="Type your ZIP code" onkeypress='validate(event)'required/>
                        </span>
<span align="center" id="zipbox2" class="nameLast">
<input type="text" class="medium" pattern="[0-9]*" name="col4" id="col4" maxlength="5" placeholder="Type your ZIP code" onkeypress='validate(event)'required/>
                </span></div>
<div align="center" class="element-name">
<span class="required"></span>
<span align="center" id="statebox" class="nameFirst">
<input type="text" class="medium" name="col1" id="col1" placeholder="" required />
<label class="subtitle">From</label>
                            </span>
<span align="center" id="statebox2" class="nameLast">
<input type="text" class="medium" name="col3" id="col3" placeholder="" required />
<label class="subtitle">To</label>
                               </span></div>
<p align="center"><input type="reset" value="Clear"></p>
</body>
</html>

some javascript !

<script src="//code.jquery.com/jquery-1.11.1.js"></script>
    <script>
    $(document).ready(function() {
    $("#col2").keyup(function() {
        var el = $(this);
        if (el.val().length === 5) {
            $.ajax({
                url: "http://zip.elevenbasetwo.com",
                cache: false,
                dataType: "json",
                type: "GET",
                data: "zip=" + el.val(),
                success: function(result, success) {
                    $("#city").val(result.city);
                    $("#col1").val(result.state);
                }
            });
        }
    });
});
    </script>
    <script>
        $(document).ready(function() {
    $("#col4").keyup(function() {
        var el = $(this);
        if (el.val().length === 5) {
            $.ajax({
                url: "http://zip.elevenbasetwo.com",
                cache: false,
                dataType: "json",
                type: "GET",
                data: "zip=" + el.val(),
                success: function(result, success) {
                    $("#city2").val(result.city);
                    $("#col3").val(result.state);
                }
            });
        }
    });
}); 
    </script>

和PHP代码来处理表单:-它是13列,但我确信其他值是正确的。- col0表示日期

<?php
require_once('recaptchalib.php');
 $privatekey = "mycaptchakey";
 $resp = recaptcha_check_answer ($privatekey,
                                 $_SERVER["REMOTE_ADDR"],
                                 $_POST["recaptcha_challenge_field"],
                                 $_POST["recaptcha_response_field"]);
 if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
   die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
        "(reCAPTCHA said: " . $resp->error . ")");
        $process = FALSE;
 } else {
   // Your code here to handle a successful verification // Your code here to handle a successful verification
 }
define('CONST_SERVER_TIMEZONE', 'EDT');
define('CONST_SERVER_DATEFORMAT', 'YmdHis');
$current_date = date("Y-m-d H:i:s");

$col0 = $_POST['col0'];
$col1 = strtoupper($_POST['col1']);
$col2 = strtoupper($_POST['col2']);
$col3 = strtoupper($_POST['col3']);
$col4 = strtoupper($_POST['col4']);

if ( isset($col1) && isset($col2) isset($col3) && isset($col4) && $error == FALSE ) {
  $process = TRUE;
} else {
  $process = FALSE;
}
$mode = "mysql";{
define ('DB_USER', 'uname');
define ('DB_PASSWORD', 'pass');
define ('DB_HOST', 'host');
define ('DB_NAME', 'dbname');
$dbc = @mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) or die('Failure: ' . mysql_error() );
mysql_select_db(DB_NAME) or die ('Could not select database: ' . mysql_error() );
$query = "INSERT INTO mytable VALUES ('$current_date','$col1','$col2','$col3','$col4')";
$q = mysql_query($query);
if (!$q) {
  exit("<p>MySQL Insertion failure.</p>");
} else {
  mysql_close();
  //for testing only
  //echo "<p>MySQL Insertion Successful</p>";
}}
  header( 'Location: http://mywebsite.com/index.php' ); 
?>

我不确定我做的是否正确,但这是我的Mytable结构:

1 - sid - int(11) AUTO_INCREMENT
2 - col0 - date
3 - col1 - text utf8_unicode_ci
4 - col2 - text utf8_unicode_ci
5 - col3 - text utf8_unicode_ci
6 - col4 - text utf8_unicode_ci
and so on up to 12 columons.

请帮忙!这是怎么回事?

编辑:

非常感谢r3wt提供的有用信息。有很多问题需要解决,尤其是PHP部分:)

好的,所以我可以修复插入。我错过了一个临界值-

$query = "INSERT INTO mytable VALUES ('$current_date','$col1','$col2','$col3','$col4')";

应该是:

$query = "INSERT INTO mytable VALUES ('','$current_date','$col1','$col2','$col3','$col4')";

这是因为所有这些表单信息都将进入一个phpGrid表我有一个隐藏列'sid',它会自动填充。

我保证下次我会准备更多的知识:)

再次感谢。

等待一秒钟后,他们已经完成了元素的输入,然后提交ajax请求。

$(function(){ 
    $("#col4").keyup(function() {
        var col4val = $(this).val();
        clearTimeout(timer);
        timer = setTimeout(function(){fillLocation(col4val)}, 1000);
    });
    var timer = null;
    function fillLocation(value){
        $.get('http://zip.elevenbasetwo.com', {zip: value} , function(data){
            var result = JSON.parse(data);
            $("#city2").val(result.city);
            $("#col3").val(result.state);
        });
    }
});

而且,你的PHP代码被认为是非常不安全的,因为你使用的是mysql。

也,我刚刚注意到一个明显的错误,你错过了$col2 isset和$col3之间的运算符,检查你的ajax,我保证你返回500内部服务器错误:

if ( isset($col1) && isset($col2) isset($col3) && isset($col4) && $error == FALSE ) {
  $process = TRUE;
} else {
  $process = FALSE;
}

也,你的查询是错误的。很明显你只是复制粘贴在一起。请阅读mysql手册中的INSERT语句,并阅读mysqlipdo的php扩展。

一个有效的mysql语句应该是这样的:

INSERT INTO mytable (column1,column2,column3) VALUES ('val1','val2','val3')
意识到这一点,您可以在PHP中构造如下语句
$query = mysql_query("INSERT INTO mytable (column1,column2,column3) VALUES ('".$val1."','".$val2."','".$val3."')");

如果你继续使用mysql,你的网站会被黑客入侵,这只是时间问题,特别是因为你没有清理你的任何数据。请做出明智的选择,使用mysqli或pdo从php连接数据库。

根据Dikei的要求,我将向您简要介绍mysql的预处理语句,以便您可以学习使用安全的方法与数据库交互。

$mysqli = new mysqli('host','username','password','databasename');
$mysqli->set_charset("utf8");
$stmt = $mysqli->prepare("INSERT INTO mytable (column1,column2,column3) VALUES (?,?,?)");//bind your variables in the same order!
//s for a string, d for a double floating point integer, and i for unsigned int.
$stmt->bind_param('sss',$col1,$col2,$col3);
if($stmt->execute()) {
    $row = $stmt->insert_id ?: null;
    if(!empty($row))
    {
        //query success
    }else{
        //query failure
    }
    $stmt->close();
}
$mysqli->close();

如果你需要更多的信息,我在这里提供了一个使用面向对象方法使用mysql的更广泛的例子(在答案的第二部分):登录会话在刷新后被破坏