udhay
udhay

Reputation: 101

Inserting multiple values to mysql from Javascript

I am adding values to tables using this command. This code helps to add multiple rows to the table and also we can delete a row by selecting the unwanted rows.

But now I have to insert those added rows from html table to mysql php table after posting it.

How to insert the added values from table to mysql table.

    <script type="text/javascript" src="main.js" charset="UTF-8"></script><link rel="stylesheet" crossorigin="anonymous" href="https:///abn/main.css"/>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $(".add-row").click(function(){
                var name = $("#name").val();
                var email = $("#email").val();
                var price = $("#price").val();
                var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + name + "</td><td>" + email + "</td><td>" + price + "</td></tr>";
                $("table tbody").append(markup);
            });

            // Find and remove selected table rows
            $(".delete-row").click(function(){
                $("table tbody").find('input[name="record"]').each(function(){
                    if($(this).is(":checked")){
                        $(this).parents("tr").remove();
                    }
                });
            });
        });    
    </script>

<table>
  <thead>
   <tr>
      <th>Select</th>
      <th>Product Description</th>
      <th>Quantity</th>
      <th>Unit Price</th>
      <th>Total Price</th>
   </tr>
  </thead>
<tbody>
   <tr>              
   </tr>
</tbody>
</table>
<button type="button" class="delete-row">Delete Row</button>
<input type="button" class="add-row btn btn-success" value="Add Row">

Upvotes: 0

Views: 551

Answers (1)

Fabien Haddadi
Fabien Haddadi

Reputation: 2080

Alternatively to the comments above, you may wrap your table inside a <form> tag, add a [Save] input that acts as a command button, so you minimise the writings to only what is validated by the user, and finally, use jQuery .serialize() method to supply data to an XHR method, such as jQuery.ajax, or jQuery.post

Part of your HTML layout, you will have added 3 input fields per table row, txtName_<pk>, txtPrice_<pk> and txtEmail_<pk> for instance, that will be automatically sent as data by .serialize().

The good thing about suffixing them with the primary key (pk) for each row, is that you can have your PHP form processor to extract this primary key, to issue the proper SQL command : INSERT, UPDATE or even REPLACE. It may also be used to report back to the user that such or such row couldn't be inserted, specifying it by its unique PK... Good luck!

EDIT Example:

in HTML

<form id="frmTable">
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Price</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><input type="hidden" name="txtName_10244" value="John Doe" />John Doe</td>
                <td><input type="hidden" name="txtEmail_10244" value="[email protected]" />[email protected]</td>
                <td><input type="hidden" name="txtPrice_10244" value="314.15" />$314.15</td>
            </tr>
        </tbody>
    </table>

<input id="cmdSave" type="submit" />

</form>

in JavaScript

$("#cmdSave").click(function() {
    $.post("processor.php", $("#frmTable").serialize())
    .done(function(data) {
        alert("Your table was saved.");
    });

});

//  You may exploit here the data (JSON) that was returned by processor.php

in PHP (processor.php)

<?php
header("Content-Type: application/json");

$data = array('success' => false, 'error' => null);
$errors = array();

foreach($_POST as $key => $val) {

    if (preg_match("/^txtName_(\d+)$/", $key, $bits)) {
        // all right, we've got a row, so let's send its data to the function that saves it.

        $ans = saveRow(
            $primaryKey = $bits[1],
            array(
                'name' => $val,
                'email' => $_POST["txtEmail_" . $primaryKey],
                'price' => $_POST["txtPrice_" . $primaryKey]
            )
        );
        if (!$ans) $errors []= "Couldn't save row #" . $bits[1];

    } 

}

if(empty($errors))
    $data['success'] = true;
else
    $data['error'] = implode('<br />', $errors);

exit(json_encode($data));
?>

Upvotes: 1

Related Questions