我正在开发一个js的小脚本,以facebook的方式编辑个人资料(点击一个按钮,编辑并保存,无需重新加载页面)。问题是,当我运行它时,ajax函数返回成功但不对数据库进行任何更改。函数os js是这样的:
$('.savebtn').click(function(){
var editdata = $(".editbox").val();
var parameter = $(this).closest("td").find("#parameter").text();
var datastring = "data="+editdata+"¶meter="+parameter;
var $t = $(this);
console.log(datastring);
$.ajax({
type: "POST",
url: BASE_URL + "/API/update_profile.php",
data: datastring,
cache: false,
success: function()
{
$t.closest('td').find('.curr_value').html(editdata);
$t.closest('td').find('.curr_value').hide;
console.log(editdata);
$(this).prev(".edit").hide();
$(this).prev(".curr_value").show();
$(this).prev('.edit_link').show();
$(this).hide();
}
});
});
(忽略$ t的东西,不知怎的,这样就可以了,但如果我使用$(this)则不行)
Ajax执行成功代码但不更新数据库上的任何内容。
数据库的PHP代码是:
<?php
include_once("../../config/connect_db.php");
include_once("../../database/cliente.php");
$parameter = $_POST['parameter'];
$data = $_POST['data'];
$id = $_SESSION['id'];
var_dump($_POST);
try {
updateProfile($parameter, $data, $id);
}
catch (PDOException $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
&GT?;
function updateProfile($parameter, $data, $id)
{
global $conn;
$stmt = $conn->prepare("UPDATE biofood.users
SET ? = ?
WHERE id = ?");
$stmt->execute(array($parameter, $data. $id));
}
编辑:正如所指出的,这可能是尝试将列名称作为参数传递的问题。将代码更改为以下内容,但没有成功:
function updateProfile($parameter, $data, $id)
{
global $conn;
$query = "UPDATE biofood.users
SET $parameter = $data
WHERE id = $id";
$stmt = $conn->prepare($query);
$stmt->execute();
}
答案 0 :(得分:0)
这一行:
$stmt->execute(array($parameter, $data. $id));
我认为应该是
$stmt->execute(array($parameter, $data, $id));
(注意$data
之后的逗号)
答案 1 :(得分:0)
这可能无法解决您的问题,但它可能会让您更好地指出问题所在。
首先,您没有检查它是否有效,因为updateProfile
函数什么也没有返回。
修改updateProfile
函数,使其返回受影响的行数。 (顺便说一下,这是编写函数的一种更安全的方法。如果在调用此函数之前可以检查或限制$参数的值,那么它将不太容易注入SQL。)
function updateProfile($parameter, $data, $id)
{
global $conn;
$stmt = $conn->prepare("UPDATE biofood.users SET $parameter = ? WHERE id = ?");
$stmt->execute(array($data, $id));
return $stmt->rowCount(); // # of rows affected
}
在调用此函数的脚本中,获取值并将其作为响应发送回去。我们将发回一个JSON。
$response = array();
try {
$response['success'] = updateProfile($parameter, $data, $id);
} catch (PDOException $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
header('Content-Type: application/json');
echo json_encode($response);
在您的JavaScript文件中,进行以下更改:
$.ajax({
type: "POST",
url: BASE_URL + "/API/update_profile.php",
data: datastring,
cache: false,
success: function (data) {
if (data.success) {
$t.closest('td').find('.curr_value').html(editdata);
$t.closest('td').find('.curr_value').hide;
console.log(editdata);
$(this).prev(".edit").hide();
$(this).prev(".curr_value").show();
$(this).prev('.edit_link').show();
$(this).hide();
}
},
dataType: 'json'
});