简体   繁体   English

将数据保存在可编辑的动态 html 表中

[英]save data in editable dynamic html table

I have created editable dynamic html table, on double click over a text the user is able to change it but the change is temporary, i wish to save it in database also.我创建了可编辑的动态 html 表,双击文本,用户可以更改它,但更改是暂时的,我也希望将其保存在数据库中。

My code for table is ( @jsfiddle )我的表格代码是( @jsfiddle

html table html表格

<table class="editableTable table table-striped table-bordered">
<thead>
    <tr>
        <th> A </th>
        <th> B </th>
        <th> C </th>
        <th> D </th>
    </tr>
</thead>
<tbody>

    <?php
    $sql=" SELECT * from orderid";
    $result = mysqli_query($con, $sql);
    if(mysqli_num_rows($result)>0)
        {
            while($row = mysqli_fetch_assoc($result))
                {?> <tr>
                        <td> <? echo $row['a']; ?> </td>
                        <td> <? echo $row['b']; ?> </td>
                        <td> <? echo $row['c']; ?> </td>
                        <td> <? echo $row['d']; ?> </td>
                    </tr>   
                <?}
        }?>

</tbody>
</table>

script code脚本代码

 $(function () 
        { 
            $("td").dblclick(function () 
                { 
                    var OriginalContent = $(this).text(); 
                    $(this).addClass("cellEditing"); 
                    $(this).html("<input type='text' value='" + OriginalContent + "' />"); 
                    $(this).children().first().focus(); 
                    $(this).children().first().keypress(function (e) 
                        {
                            if (e.which == 13)
                                {   
                                    var newContent = $(this).val(); 
                                    $(this).parent().text(newContent); 
                                    $(this).parent().removeClass("cellEditing"); 
                                } 
                        }); 
                    $(this).children().first().blur(function()
                        {
                            $(this).parent().text(OriginalContent); 
                            $(this).parent().removeClass("cellEditing"); 
                        }); 
                }); 
        });

code i wish to use to edit the entry is我想用来编辑条目的代码是

$sql1="UPDATE tablename set A='".$a."', B= '".$b."', C= '".$c."', D= '".$d."' WHERE id='".$id."' ";
if(!mysqli_query($con,$sql1))
    {
        die('Error:' . mysqli_error($con));
    }

table view表视图

id  A  B  C  D
1   a  b  c  d

Can anyone please tell me how i can save the new entry in database谁能告诉我如何在数据库中保存新条目

Here is a working (at the client) jsfiddle example .这是一个工作(在客户端) jsfiddle示例。

I fix you a remove class problem, $(this) was the input and by doing $(this).parent().text("") then $(this) does not exist to get his parent again.我为您修复了一个删除类问题,$(this) 是输入,通过执行 $(this).parent().text("") 然后 $(this) 不存在以再次获取他的父级。

So you can print your table like this所以你可以像这样打印你的表格

<tr data-id="1"><!-- Include here the row id -->
    <td data-name="a"> a1 </td><!-- Include each cell's name -->
    <td data-name="b"> b1 </td>
    <td data-name="c"> c1 </td>
    <td data-name="d"> d1 </td>
</tr>

I added you a save function我给你加了保存功能

    var saveChanges = function(cell){
        $.ajax({
            type: 'POST',
            url: 'save_changes.php',
            dataType: "json",
            data: getData(cell),
            success: function (json){
                if(json.error){
                    console.log('Error : '+json.error);
                }else{
                    console.log('Data saved.');
                }
            },
            error: function(){
                console.log('Can not connect to the server.');
            }
        });
    }

And a get data function和一个获取数据的功能

var getData = function(cell){
    var data = {
        "id" : $.trim(cell.parent().data('id')), // Get row id
        "name" : $.trim(cell.data('name')), // Get the tuple name
        "value" : $.trim(cell.html()) // Get new value
    };
    return data;
}

On the server you need a php file to save the data, the code should be something like在服务器上你需要一个 php 文件来保存数据,代码应该是这样的

    // Server Code
    // file "save_changes.php"

    // SQL injection protect
    // http://www.bitrepository.com/sanitize-data-to-prevent-sql-injection-attacks.html
    function sanitize($data){
        // remove whitespaces (not a must though)
        $data = trim($data);

        // apply stripslashes if magic_quotes_gpc is enabled
        if(get_magic_quotes_gpc()){
            $data = stripslashes($data);
        }

        // a mySQL connection is required before using this function
        $data = mysql_real_escape_string($data);

        return $data;
    }

    if(isset($_POST["id"]) && isset($_POST["name"]) && isset($_POST["value"])){
        $id = sanitize($_POST["id"]);
        $name = sanitize($_POST["name"]);
        $value = sanitize($_POST["value"]);
        // Save Data
            // Here you save your data
            $sql1="UPDATE tablename set '".$name."'='".$value."' WHERE id='".$id."' ";
            if(!mysqli_query($con,$sql1)){
                echo '{"error":"'.mysqli_error($con).'"}';
            } else {
                // Report ok
                echo '{"status":"success"}';
            }
    } else {
        echo '{"error":"missing data"}';
    }

Be carefull with the spaces, i added some $.trim() to remove them.小心空格,我添加了一些 $.trim() 来删除它们。 If new content is the same with the old, no change will be send to the server, you may want to disable it.如果新内容与旧内容相同,则不会向服务器发送任何更改,您可能需要禁用它。

 $(function() { var getData = function(cell) { var data = { "id": $.trim(cell.parent().data('id')), "name": $.trim(cell.data('name')), "value": $.trim(cell.html()) }; return data; } var saveChanges = function(cell) { $.ajax({ type: 'POST', url: 'save_changes.php', dataType: "json", data: getData(cell), success: function(json) { if (json.error) { console.log('Error : ' + json.error); } else { console.log('Data saved.'); } }, error: function() { console.log('Can not connect to the server.'); } }); /* // Server Code // file "save_changes.php" // SQL injection protect // http://www.bitrepository.com/sanitize-data-to-prevent-sql-injection-attacks.html function sanitize($data){ // remove whitespaces (not a must though) $data = trim($data); // apply stripslashes if magic_quotes_gpc is enabled if(get_magic_quotes_gpc()){ $data = stripslashes($data); } // a mySQL connection is required before using this function $data = mysql_real_escape_string($data); return $data; } if(isset($_POST["id"]) && isset($_POST["name"]) && isset($_POST["value"])){ $id = sanitize($_POST["id"]); $name = sanitize($_POST["name"]); $value = sanitize($_POST["value"]); // Save Data // Here you save your data $sql1="UPDATE tablename set '".$name."'='".$value."' WHERE id='".$id."' "; if(!mysqli_query($con,$sql1)){ echo '{"error":"'.mysqli_error($con).'"}'; } else { // Report ok echo '{"status":"success"}'; } } else { echo '{"error":"missing data"}'; } */ } $("#myData td").dblclick(function() { var OriginalContent = $.trim($(this).text()); $(this).addClass("cellEditing"); $(this).html("<input type='text' value='" + OriginalContent + "' />"); $(this).children().first().focus(); $(this).children().first().keypress(function(e) { if (e.which == 13) { var newContent = $(this).val(); var cell = $(this).parent(); cell.text(newContent); cell.removeClass("cellEditing"); if ($.trim(newContent) != OriginalContent) saveChanges(cell); } }); $(this).children().first().blur(function() { var cell = $(this).parent(); cell.text(OriginalContent); cell.removeClass("cellEditing"); }); }); });
 .editableTable { border: solid 1px; width: 100% } .editableTable td { border: solid 1px; } .editableTable .cellEditing { padding: 0; } .editableTable .cellEditing input[type=text] { width: 100%; border: 0; background-color: rgb(255, 253, 210); }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="myData" class="editableTable table table-striped table-bordered"> <thead> <tr> <th>A</th> <th>B</th> <th>C</th> <th>D</th> </tr> </thead> <tbody> <tr data-id="1"> <!-- Include here the row id --> <td data-name="a">a1</td> <!-- Include each cell's name --> <td data-name="b">b1</td> <td data-name="c">c1</td> <td data-name="d">d1</td> </tr> <tr data-id="2"> <!-- Include here the row id --> <td data-name="a">a2</td> <!-- Include each cell's name --> <td data-name="b">b2</td> <td data-name="c">c2</td> <td data-name="d">d2</td> </tr> </tbody> </table>

$("#save").click(function () {
    var dataA='Data in A td';
    $.ajax({
        type: 'POST',
        url: 'your php page where you do the insert',
        dataType: "json",//response from php page
        data: {
            dataA: dataA//data you will save in database
            },
        success: function (data) {
            alert("Success");
        },
        error: function (data) {
           alert("Error");
        }


    });
});

You can do it like this.你可以这样做。 Just change the url of the php page then you can also change the dataType into what ever you want the php page to respond example are text and html and more只需更改 php 页面的 url,然后您还可以将 dataType 更改为您希望 php 页面响应的内容,例如文本和 html 等等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM