一个可能的事情是在你的桌子上使用属性。
<table id="table-to-click">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Bin1</th>
<th>Bin2</th>
<th>Bin3</th>
</tr>
</thead>
<tbody>
<tr data-id="1" class="table-tr">
<td data-prop="id" class="t-id">1</td>
<td data-prop="name" class="t-id">Mila</td>
<td data-prop="bin1" class="t-id">0</td>
<td data-prop="bin2" class="t-id">0</td>
<td data-prop="bin3" class="t-id">1</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
$(function() {
//On click on a td in this table
$("table.table-to-click > tbody > tr.table-tr td").on('click', function(e) {
//Get field in database to update
var fieldName = $(this).attr('data-prop');
//Get id in database (easier that read first td's value)
var id = $(this).parent().attr('data-id');
//Call server with datas
$.ajax({
method: "POST",
url: "update-field.php",
data: {
field: fieldName,
id: id
}
});
};
});
</script>
上面的代码显示一个表格,点击表格单元格发送请求以更新给定字段。请参阅 jQuery 和 AJAX。注意:data-prop 是数据库中字段的名称。
下面的代码是你的页面update-field.php,它接收请求,并在数据库中更新
if (empty($_POST['field']) || empty($_POST['id'])) {
exit();
}
$fields = ["name", "bin1", "bin2", "bin3"];
//It is only possible to update field in $fields array,
//This is for security reason (to not update id for example)
if (! in_array($_POST['field'], $fields)) {
exit();
}
$db = new PDO('mysql:host=localhost;dbname=yourdbname;charset=utf8', 'yourusername', 'yourpassword');
$stmt = $db->prepare("UPDATE yourTable SET :fieldname = (:fieldname + 1) % 2 WHERE id = :id");
$stmt->execute(array(
'fieldname' => mysql_real_escape_string($_POST['field']),
'id' => intval($_POST['id']),
));
参见PDO 和prepared statements。