save values from editable table using php

后端 未结 3 2228
攒了一身酷
攒了一身酷 2021-02-09 14:58

Hi I have a table generated from php, it is editable, I want to save edited values to database. I have no Idea how can I do this as there are many rows(dynamic) on a page. Here

3条回答
  •  旧时难觅i
    2021-02-09 15:33

    To save the whole table, you could leave the row-level update buttons out, and have a single save button:

    
    

    The msg area is to display feed-back from the server when the save-operation is performed.

    Then you would add this JavaScript to handle the click of the save button:

    $('#save').click(function() {
        var data = []; 
        $('td').each(function() {
            var row = this.parentElement.rowIndex - 1; // excluding heading
            while (row >= data.length) {
                data.push([]);
            }
            data[row].push($(this).text());
        });
        $.post('savetable.php', {table: data}, function (msg) {
            $('#msg').text(msg);
        });
    });
    

    This will transform the HTML table contents, without header row, to a JavaScript matrix, which then is sent to savetable.php for processing.

    In PHP you would then use $_POST['table'] to access that array. When you implement this, first debug, and do a var_dump($_POST['table']) to make sure the data was transferred correctly, and it has the array structure you expect.

    Then loop over that array to insert the rows into your database. You can use mysqli or PDO for this.

    The PHP script savetable.php should only echo one message: a confirmation ("the table was saved successfully") or an error message ("a problem occurred. Your data was not saved.").

    It should not reproduce the HTML of the table, since that is already displayed in the browser. Whatever PHP prints will be used by the JavaScript code to be displayed below the save button.

    Here is how savetable.php could look like. But please debug carefully, I did not test this code. And before it works, you first need to set up your database model of course:

    $db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8mb4', 
                  'username', 'password');
    // Configure that all database errors result in an exception:
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    try {
        // Make a transaction: this allows to rollback any of the changes
        // if anything goes wrong before the end of it. 
        $db->beginTransaction();
        // First delete all rows.
        $db->exec("DELETE FROM mytable");
        // Prepare a statement that will be executed for each row.
        // Needs to be extended for all columns:
        $stmt = $db->prepare("INSERT INTO mytable (sl_num, product_id, product_name)
                              VALUES (?, ?, ?)");
    
        foreach ($_POST('table'] as $row) {
            $stmt->execute($row); // the columns are passed to the prepared statement.
        }
        // All went well: commit the changes.
        $db->commit();
        echo "Table saved successfully";
    } catch(PDOException $e) {
        // Something went wrong: roll back any changes made
        $db->rollback();
        echo "An error occurred: " . $e->getMessage();
    }
    

提交回复
热议问题