简体   繁体   中英

Save data from dataTable to database

how can I save all my datatable data to my database?, im using jquery and php to do this dynamic.

        $('#bot_guar').click( function () {
        //var rows = $("#tabla1").dataTable().fnGetNodes(); 

        var oTable = $('#tabla1').DataTable();
        var data1 = oTable.rows().data();
        //alert(data1.length);  
        $.ajax({
        type:"POST",
        dataType:'json',
        url: "<?= Router::Url(['controller' => 'cab_facturas', 'action' => 'addDetFac'], TRUE); ?>/",//teacher//getdata/3
        data:data1, 
        success: function(data){    
            alert(data);
        }//success
        });     

    }); 

this is what I had to POST the data from datatable, but I dunno why is the function to send to my php function that will insert.

You can consume the data object sent from your AJAX call as POST parameters or query string parameters depending on your settings. Consider you want to access firstname, lastname and email from your server side script. It can be done using:

$firstname = _POST['firstname'];
$lastname = _POST['lastname'];
$email = _POST['email'];

Now, Connect to your database and insert this data through your php script:

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";

if ($conn->query($sql) === TRUE) {
  echo "New record created successfully";
} else {
  echo "Error: " . $sql . "<br>" . $conn->error;
}

Its good practice to send a response to your call back functions so you can do this:

echo json_encode(array('status'=>"Success", message=""));

Your call back function will contain the data sent back from the php file. Since we are sending back a json string, we can make an object of it like this:

var myCallbackFunction = function(data){
var d = $.parseJSON(data)[0];
if(d.Status=="Success"){
//reload your datatable ajax
}else{
alert(d.message);
}
}

I hope that helped!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM