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

时间:2015-09-11 04:56:53

标签: javascript jquery html mysql ajax

我创建了可编辑的动态html表,双击文本后用户可以更改它,但更改是暂时的,我也希望将其保存在数据库中。

我的表格代码是(@jsfiddle

html table

<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>

脚本代码

 $(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"); 
                        }); 
                }); 
        });

我想用来编辑条目的代码是

$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));
    }

表格视图

id  A  B  C  D
1   a  b  c  d

任何人都可以告诉我如何在数据库中保存新条目

1 个答案:

答案 0 :(得分:1)

这是一个工作(在客户端)jsfiddle示例。

我修复了一个删除类问题,$(this)是输入,通过执行$(this).parent()。text(&#34;&#34;)然后$(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>

我添加了一个保存功能

    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.');
            }
        });
    }

获取数据功能

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;
}

在服务器上你需要一个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"}';
    }

小心空格,我添加了一些$ .trim()来删除它们。 如果新内容与旧内容相同,则不会向服务器发送任何更改,您可能需要将其禁用。

&#13;
&#13;
$(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");
    });
  });
});
&#13;
.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);
}
&#13;
<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>
&#13;
&#13;
&#13;