0

I would like to ask for support to be able to insert the data I bring into a table and insert it into a table in my mysql database.

enter image description here

I have a button that I want to click on to save the data in a mysql table.

How do I pass the data that is in the table and send it to the database?

Can I do it using AJAX?

1
  • Share the code of what you have tried. Commented Jun 14, 2020 at 5:39

1 Answer 1

1

Yes - you can save using AJAX. One possible approach:

  1. When a user clicks save, run a loop in javascript to gather the fields of each row into an object, and add it to an array; a structure like:
var table_data = [
    {field1:value1, field2:value2, field3: value3...}, // one of these for every row in the table
]

fieldX would be the names of your column headers, and valueX would be the values of those fields.

  1. Using ajax, post the data to a server-side script. An example using jQuery:
$ajax.({
    type : 'POST',
    url  : 'script.php',
    data : { 'submit_data' : table_data } 
});
  1. On the server in a file called script.php, receive the POST'ed data, and then run a loop over the data to save each row to the table. Here's a sparse example, using PHP and mysqli:
$mysqli = database_connection();
$data = $_POST['submit_data']; //sanitize this!

foreach($data as $row){
    $mysqli->query( "INSERT INTO data_table (field1, field2, field3) VALUES($row['field1'], $row['field2'], $row['field3'])" );
}

Bear in mind the above is very unsafe for a production environment; at a minimum, you should use prepared statements and parameter binding to insert the data: https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php

I hope this gets you going. GL!

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your comment. How can I extract the data from the table? I use datatable plugin. I would like to extract the data from the datatable and send it through an array using ajax. Could you help me please.
I'm not familiar enough with datatable to know whether it has functionality to convert the table data into an array, but, using jquery, you can do something like: ``` var table_rows = array(); $('table tbody tr').each(function(){ var row = array(); $(this).find('td').each(function(){ row.push( $(this).text() ); }); table_rows.push(row); }) ``` Bear in mind the above is an array of arrays, and not an array of objects that contain the field names

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.