PHP和jQuery插入到MySQL
我想用jQuery将数据插入mySQL。代码不会返回任何错误,也不会返回任何结果。请帮我解决这个问题。PHP和jQuery插入到MySQL
$(document).ready(function() {
$("#submit").click(function() {
var data;
var eid = 101;
data = "eid=" + eid;
for (i = 0; i <= 10; i++) {
data += "&Text_" + (i + 1) + "=" + $("#Text_" + (i + 1)).val();
data += "&Amount_" + (i + 1) + "=" + $("#Amount_" + (i + 1)).val();
}
$.ajax({
type: "POST",
url: "process.php",
cache: false,
data: data,
dataType: "json",
success: function(response) {
if (!response.error) {
$("#msg").addClass('alert-success').html(response.msg);
} else {
$("#msg").addClass('alert-danger').html(response.msg);
}
}
});
});
});
<tr>
<td><input type="text" value="Allowance1 " name="Text[]" id="Text_1" /></td>
<td><input type="text" value="1001.00" name="Amount[]" id="Amount_1" /></td>
</tr>
<tr>
<td><input type="text" value="Allowance 2" name="Text[]" id="Text_2" /></td>
<td><input type="text" value="1002.00" name="Amount[]" id="Amount_2" /></td>
</tr>
<tr>
<td><input type="text" value="Allowance 3" name="Text[]" id="Text_3" /></td>
<td><input type="text" value="1003.00" name="Amount[]" id="Amount_3" /></td>
</tr>
我也加入process.php片段,以便知道哪里是错误。
process.php
$eid=$_POST['eid'];
$length = sizeof($_POST["Text"]);
$i=1;
while ($i<=$length){
if(!empty($_POST['Text'][$i])) {
$Text = $_POST['Text'][$i];
$Amount = $_POST['Amount'][$i];
$msg = array('status' => !$error, 'msg' => 'Failed! updation-1');
if(!$error) {
$sql = "UPDATE TblCustom SET Text='" . $Text . "', Amount='" . $Amount ."' WHERE ID='$eid'";
$status = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
$msg = array('error' => $error, 'msg' => 'Success! updation : '. $sql);
}
else {
$msg = array('error' => $error, 'msg' => 'Failed! updation-2 ');
}
}
echo json_encode($msg);
}
感谢
你有3个问题。
问题一和二是相关的。首先,您指定的是dataType: 'json'
,但是您的数据格式为application/x-www-form-urlencoded
。其次,你的PHP脚本预计数据将在以下格式:
$_POST = [
'Text' => ['text_1', 'text_2', 'text_3'],
'Amount' => ['amount_1', 'amount_2', 'amount_3']
];
虽然数据看起来是这样的:
$_POST = [
'Text_1' => 'text_1',
'Text_2' => 'text_2'
// and so on
];
单修复这个问题的方法如下:
$(document).ready(function() {
$("#submit").click(function() {
const data = {
// we are grabbing all inputs with name=Text[]
// and mapping them to array containing their values.
// The `...` is a spread operator introduced
// with the new js standard (ES6),
// that converts jQuery object to regular javascript
// array of inputs.
// you can do all of this with a for loop, but the map way
// is prefered
Text: [...$('input[name="Text[]"]')].map(input => input.value),
Amount: [...$('input[name="Amount[]"]')].map(input => input.value)
}
$.ajax({
type: "POST",
url: "process.php",
cache: false,
data: data,
dataType: "json",
success: function(response) {
if (!response.error) {
$("#msg").addClass('alert-success').html(response.msg);
} else {
$("#msg").addClass('alert-danger').html(response.msg);
}
}
});
});
});
第三个问题是已经创建了SQL注入漏洞。这意味着一些坏人可以注入和SQL语句到Text
变量,然后你直接把你的SQL更新,因此他可以做他想做的任何事情(例如,删除所有数据库)。
的解决方案是简单:使用PDO和bindValue
方法。
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$conn = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
// 500 means internal server error
// that's handy information for the client-side
http_send_status(500);
echo json_encode([
'error' => [
'message' => 'Unable to connect to database'
]
]);
exit;
}
$eid = $_POST['eid'];
$Text = $_POST['Text'][$i];
$Amount = $_POST['Amount'][$i];
$sql = "UPDATE TblCustom SET Text = :text, Amount = :amount WHERE ID = :id";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':text', $Text);
$stmt->bindValue(':amount', $Amount);
$stmt->bindValue(':id', $eid);
if (!$stmt->execute()) {
// 400 means something went wrong when updating
// also a handy information for the client-side
http_send_status(400);
echo json_encode([
'error' => [
'message' => 'Unable to update'
]
]);
exit;
}
// 204 measn everything went okay, and we don't return anything
http_send_status(204);
exit;
提示:如果您要发送正确的状态码jQuery的,您可以处理这样的错误:
$.ajax({
// ...
success: function(response) {
// this code will be executed
// only when status code == 2xx
},
error: function(response) {
// this code will be executed
// only when status code == 4xx | 5xx (if I remember correctly)
},
always: function(response) {
// this code will be executed no matter what
// as the name implies
},
});
所以没有需要额外的if语句。
感谢SQL注入部分。给定的代码是一个很好的例子如何不做网站和数据库之间的通信 – Serverfrog
@Kamil Latosinski感谢代码和信息的SQL注入,这仍然在测试阶段将照顾安全措施根据您的建议。我没有找到任何对“$ i”的引用。** $ Text = $ _POST ['Text'] [$ i]; ** – Gawai
好吧,没有一个。 PHP代码示例仅演示了如何在您的案例中使用PDO。您必须根据需要调整代码。 –
index.php
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form id="form_signup" name="form_signup">
<tr>
<td><input type="text" value="Allowance1 " name="Text[]" id="Text_1" /></td>
<td><input type="text" value="1001.00" name="SAmount[]" id="Amount_1" /></td>
</tr>
<tr>
<td><input type="text" value="Allowance 2" name="Text[]" id="Text_2" /></td>
<td><input type="text" value="1002.00" name="SAmount[]" id="Amount_2" /></td>
</tr>
<tr>
<td><input type="text" value="Allowance 3" name="Text[]" id="Text_3" /></td>
<td><input type="text" value="1003.00" name="SAmount[]" id="Amount_3" /></td>
</tr>
<input type="submit" name="signup" value="Sign Up!"/>
</form>
<script>
$(document).ready(function() {
$("#form_signup").click(function() {
$.ajax({
type: "POST",
url: "process.php",
cache: false,
data: $(this).serialize(),
success: function(response) {
alert(response);
if (!response.error) {
$("#msg").addClass('alert-success').html(response.msg);
} else {
$("#msg").addClass('alert-danger').html(response.msg);
}
}
});
});
});
</script>
</body>
</html>
process.php
<?php
print_r($_POST);
?>
对你做了什么或者是什么问题的解释?一个代码块本身并不是那么有用。 –
@Nikit Barochiya数据:$(this).serialize(),没有帮助 – Gawai
工作正常并且serialize()获取表单中的所有数据。检查js文件工作是否正常 –
什么是您指定'数据类型,它使用的是在process.php –
代码:“JSON”',而是你正在使用的实际格式是'应用程序/ x-WWW的形式,urlencoded' (名称=值,用&分隔)。 这可能是你的PHP脚本失败的原因。删除'dataType'属性并检查是否有帮助。 –
@RohitAilani process.php添加片段 – Gawai