【发布时间】:2013-04-16 13:57:27
【问题描述】:
使用 jQuery/AJAX,我正在尝试 a) 更新包含 $firstname、$lastname 和自动递增的 $user_id 的 HTML 表中的现有记录和 b) 返回新的数据库条目及其 ID 号,并在 HTML 中显示它们而无需刷新页面。
计划是使用 jQuery .on("click"...) 获取两个名称字段中的数据并触发 php 文件 add-user.inc.php 插入这些,留下 $user_id 的值为NULL,所以它自动递增:
$(document).on("click", ".insert", function(){
var firstname = $('input.newdata[name="firstname"]').val();
var lastname = $('input.newdata[name="lastname"]').val();
$.ajax({ // begin insert ajax
url: "php-includes/add-user.inc.php",
type: "GET",
data: { // begin insert data
'firstname': firstname,
'lastname': lastname
}, // end insert data
}); // end insert ajax
// closing }); comes later
然后,在 click 事件中,为了使浏览器可以正确识别新插入的行以进行进一步的数据操作而无需刷新页面,使用另一个 AJAX 调用来检索这个新插入记录的 id 值:
$.ajax({ // begin retrieve ajax
url: "php-includes/retrieve-user_id.inc.php",
data: "",
datatype: "application/json",
type: 'get',
success: function(data) {
var user_id = data;
// declare var newrecord which is a table row containing
// <tr> with the variable user_id as its ID
// and <td>s containing inputs containing the newly inserted data
$('table tr:last').before(newrecord); // .. and insert this into the table
}, // end retrieve data
}); // end retrieve ajax
});
add-user.inc.php:
// connect to db
$firstname = $_GET['firstname'];
$lastname = $_GET['lastname'];
$insert_user_sql = "INSERT INTO `table` (user_id, firstname, lastname)
VALUES (NULL,'$firstname','$lastname')";
$result = $db->query($insert_user_sql);
检索-user_id.inc.php
// connect to db
$retrieve_user_sql = "SELECT `user_id` from `table` ORDER BY `user_id` DESC LIMIT 1";
$retrieve_user_result = $db->query($retrieve_user_sql);
$retrieve_user_num_rows= $retrieve_user_result->num_rows;
if ($retrieve_user_num_rows > 0) {
while ($row = $retrieve_user_result->fetch_object()) {
$user_id = $row->user_id;
$result = ($user_id + 1);
}
} else {
$result = 1;
}
echo $result;
插入到 HTML 中的 user_id 编号间歇性错误,有时增加 2 而不是 1,有时不增加,给出两个具有相同 ID 的表行,直到刷新页面并通过纯 PHP 检索到正确的 ID 号。如果在插入之间没有进行页面刷新的情况下输入了多条记录,这会导致问题,因为单个 ID 可以定位多行。
如果在每次插入之间执行页面刷新,则没有问题。
有什么想法吗?提前致谢。
【问题讨论】:
-
不要提出 2 个请求..添加用户时将 ID 发回
-
嗨查理,这是 Moonwave 的建议 - 你能告诉我如何从 add-user.inc.php 取回这些数据吗?
-
只是回显该值。您的插入查询应自动返回新 ID。不确定您为
$db使用什么框架或类 -
我正在使用 MySQL。整个 add-user.inc.php 现在是: include 'connect.inc.php'; $firstname = $_POST['firstname']; $lastname = $_POST['*/lastname']; $insert_user_sql = "INSERT INTO
table(user_id, firstname, lastname) VALUES (NULL,'$firstname','$lastname')"; $result = $db->query($insert_user_sql);回显$结果;但 $result 的值始终为 1。