save values from editable table using php

后端 未结 3 2211
攒了一身酷
攒了一身酷 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条回答
  • 2021-02-09 15:15

    Let me give you with the best way First your database tables have spaces: correct that e.g.

    from $row["Initial Stock"] to $row["Initial_Stock"]

    Then i will propose you use ajax instead of wasting time clicking buttons

    The HTML Page

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
     <script>
    $(function(){
    
        $("#loading").hide();
        //acknowledgement message
        var message_status = $("#status");
        $("td[contenteditable=true]").blur(function(){
            var field_userid = $(this).attr("id") ;
            var value = $(this).text() ;
    
    
    
            $.post('update.php' , field_userid + "=" + value, function(data){
    
    
    
                if(data != '')
                {
                    message_status.show();
                    message_status.text(data);
                    //hide the message
                    setTimeout(function(){message_status.hide()},1000);
                }
            });
        });
    
    
    
    
    });
    </script>
    
    
    <style>
    table.zebra-style {
        font-family:"Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
        text-align:left;
        border:1px solid #ccc;
        margin-bottom:25px;
        width:100%
    }
    table.zebra-style th {
        color: #444;
        font-size: 13px;
        font-weight: normal;
        padding: 5px 4px;
    
    }
    table.zebra-style td {
        color: #777;
        padding: 4px;
        font-size:13px;
    
    }
    table.zebra-style tr.odd {
        background:#f2f2f2;
    }
    
    
    #status { padding:10px; position:fixed; top:10px; border-radius:5px; z-index:10000000; background:#88C4FF; color:#000; font-weight:bold; font-size:12px; margin-bottom:10px; display:none; width:100%; }
    #loading { padding:10px; position:absolute; top:10px; border-radius:5px; z-index:10000000; background:#F99; color:#000; font-weight:bold; font-size:12px; margin-bottom:10px; display:none; width:100%; }
    </style>
    
     <div id="status"> </div>
     <div id="loading"></div>
    
    
    
    
    
    <table id="tableID" border="0"  class="sortable table zebra-style">
    
    
    <thead>
      <tr>
        <th>Sl Number</th>
        <th>Product Id</th>
        <th>Product Name</th>
        <th>Product Catagory</th>
        <th>Retal Price</th>
        <th>Max Price</th>
        <th>Min Price</th>
        <th>Initial Stock</th>
        <th>Quantity Sold</th>
        <th>Current Stock</th>
        <th>Last Order</th>
        <th>Edit/Update</th>
      </tr>
    </thead>
    <tbody  class="list">
      <?php do { ?>
    
    
      <tr>
        <td contenteditable="true" id="Row_Number:<?php echo $row["Row_Number"]; ?>"><?php echo $row["Row_Number"]; ?></td>
        <td contenteditable="true" id="Product_Id:<?php echo $row["Product_Id"]; ?>"><?php echo $row["Product_Id"]; ?></td>
        <td contenteditable="true" id="Product_Name:<?php echo $row["Product_Name"]; ?>"><?php echo $row["Product_Name"]; ?></td>
        <td contenteditable="true" id="Product_Catagory:<?php echo $row["Product Id"]; ?>"><?php echo $row["Product_Catagory"]; ?></td>
        <td contenteditable="true" id="Retal_Price:<?php echo $row["Retal_Price"]; ?>"><?php echo  $row["Retal_Price"]; ?></td>
        <td contenteditable="true" id="Max_Price:<?php echo $row["Max_Price"]; ?>"><?php echo $row["Max_Price"]; ?></td>
        <td contenteditable="true" id="Min_Price:<?php echo $row["Min_Price"]; ?>"><?php echo  $row["Min_Price"]; ?></td>
        <td contenteditable="true" id="Initial_Stock:<?php echo $row["Initial_Stock"]; ?>"><?php echo  $row["Initial_Stock"]; ?></td>
        <td contenteditable="true" id="Quantity_Sold:<?php echo $row["Quantity_Sold"]; ?>"><?php echo  $row["Quantity_Sold"]; ?></td>
        <td contenteditable="true" id="Last_Order:<?php echo $row["Last_Order"]; ?>"><?php echo  $row["Last_Order"]; ?></td>
        <td contenteditable="true" id="Last_Order:<?php echo $row["Last_Order"]; ?>"><?php echo  $row["Last_Order"]; ?></td>
        <td contenteditable = 'false'></td>";
    
    
    
        </tr>
    
        <?php } while($row = $result->fetch_assoc()) ?>
     </tbody>
    </table>
    

    And the update php page

       <?php  
    
    
    $db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 
                      'username', 
                      'password',
                      array(PDO::ATTR_EMULATE_PREPARES => false,
                      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
    
    
    ?>
    
    <?php
    if(!empty($_POST))
    {
        //database settings
    
        foreach($_POST as $field_name => $val)
        {
            //clean post values
            $field_id = strip_tags(trim($field_name));
    
            //from the fieldname:user_id we need to get user_id
            $split_data = explode(':', $field_id);
            $product_id = $split_data[1];
            $field_name = $split_data[0];
            if(!empty($product_id) && !empty($field_name) && !empty($val))
            {
    
                $affected_rows = $db->exec("UPDATE yourtable SET $field_name = '$val' WHERE product_ID = $product_id");
                echo $affected_rows;
    
                echo "Updated";
            } else {
                echo "Invalid Requests";
            }
        }
    } 
    
    else {
        echo "Invalid Requests";
    }
    ?>
    
    0 讨论(0)
  • 2021-02-09 15:32

    What you can do is ajax call to a php with the id of the row you want to save and the new data. Then use PDO to connect to the database and update the information. After that is done, use javascript to edit the table itself.

    So what you need to do is look up how to use ajax calls and use PDO. I suggest when you echo the table itself <button href = '#' onclick="updateRow('. $row['Row Number'] .')">Update</a></td> where Row Number is the ID in the database and updateRow() is the javascript function you will create to get the new information and send it via ajax. Don't use mysql_*, because it is not supported in php 7 and it will die soon. Look up PDO instead.

    0 讨论(0)
  • 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:

    <button id="save">Save</button>
    <div id="msg"></div>
    

    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();
    }
    
    0 讨论(0)
提交回复
热议问题