将值从HTML表保存到数据库

save values from html table to database

本文关键字:保存 数据库 HTML      更新时间:2023-09-26

我有一个HTML表,显示来自数据库的值。我有一个javascript,使我能够编辑这些数据,但我不能弄清楚如何将其保存回数据库使用php。我发现了一些信息,我应该使用xmlhttprequests,但我不知道如何做到这一点。有什么建议吗?非常感谢你的帮助。下面的代码;

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Untitled Document</title>
    <script type="text/javascript"><!--
    function edit_input(obj) {
    var is_checked = obj.checked;
    while (obj.tagName!='TR')
    obj = obj.parentNode;
    var td = obj.getElementsByTagName('TD');
    var len = td.length;
    if (!is_checked) {
    for (var i=0; i<len; i++)
    if (td[i].className=='editable')
    td[i].innerHTML = td[i].firstChild.value;

    } else {
    var input;
    for (var i=0; i<len; i++)
    if (td[i].className=='editable') {
    input = document.createElement('INPUT');
    input.value = td[i].innerHTML;
    td[i].innerHTML = '';
    td[i].appendChild(input);
    }
    }
    }

    --></script>

    </head>
    <body>
    <table border="1">
    <tr>
         <th width="56">Branch ID</th>
    <th width="75">Branch Name</th>
         <th width="75">Branch Personnel</th>                            
         <th width="105">Branch Headquaters</th>
    <th width="50">Edit</th>
    </tr>
<?php
$result = mysql_query($query );
    while ($row= mysql_fetch_array($result)) { ?>
         <tr>
             <td class="editable"><?php echo $row['branchid'];?></td>
             <td class="editable"><?php echo $row['branchname'];?></td>     
             <td class="editable"><?php echo $row['branchpersonnel'];?></td>
             <td class="editable"><?php echo $row['branchhq'];?></td>   
        <td><input type="checkbox" onclick="edit_inpu(this);">Edit</td>  
         </tr>                                          
<?php } ?>
    <tr><td><input type="submit" name="editbranch" class="button2"       value="Update"/></td></tr> 
</table>    
    </body>
    </html>

如果使用jQuery没有问题,也许使用JEditable之类的东西是一个解决方案。当您单击表格中的单元格时,它会变成一个文本字段,当按enter键或离开焦点时,它会向服务器发出一个web请求,在那里您可以进行更改。

请看这个jsfiddle脚本的例子。它真的很容易使用。您需要做的唯一一件事是为表格单元格提供一个id,该id将被发送到您要保存它的页面。

让脚本通过XMLHttpRequest向PHP脚本发出Ajax请求,PHP脚本将值保存回数据库。

URL可以是这样的:updatetable.php?row=0&col=0&data=1234

可以使用jquery,非常流行。

你必须下载这个库并把它包含在标题

http://code.jquery.com/jquery-1.7.min.js

,这里是如何使用jquery ajax请求:

http://api.jquery.com/jQuery.ajax/

url参数是您发送值的位置,以便像post一样保存它们