从serializeArray()
获取数据并将其用于PHP和MySQL更新操作,您需要遵循以下步骤:
serializeArray()
方法获取表单数据:var formData = $('#your-form-id').serializeArray();
serializeArray()
的结果转换为JSON字符串,以便将其发送到服务器:var jsonString = JSON.stringify(formData);
$.ajax({
url: 'your-php-file.php',
type: 'POST',
data: {formData: jsonString},
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
<?php
// 连接数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 解析JSON字符串
$jsonData = file_get_contents('php://input');
$data = json_decode($jsonData, true);
// 遍历数据并更新MySQL数据库
foreach ($data as $row) {
$key = $row['name'];
$value = $row['value'];
// 构建更新语句
$sql = "UPDATE your_table SET $key = '$value' WHERE your_condition";
// 执行更新语句
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
// 关闭数据库连接
$conn->close();
?>
请注意,您需要根据实际情况替换your-form-id
、your-php-file.php
、your_table
和your_condition
。同时,为了防止SQL注入,建议使用预处理语句来执行更新操作。
领取专属 10元无门槛券
手把手带您无忧上云