gpt4 book ai didi

php - 我正在开发一个将信息提交到数据库的 AJAX 表单。它在到达插入函数时记录错误

转载 作者:行者123 更新时间:2023-11-29 01:29:37 28 4
gpt4 key购买 nike

我整理了一个 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());}
?>

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

<? 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

<?$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);

?>

这就是全部(当然,我去掉了品牌部分)。就像现在一样,它记录“出了点问题”

something went wrong

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

几个小时以来,我一直在修补这个东西,但无法弄清楚为什么它会失败。

最佳答案

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

$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_* 函数,并恢复为参数化查询。查看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']));

关于php - 我正在开发一个将信息提交到数据库的 AJAX 表单。它在到达插入函数时记录错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20334823/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com