简体   繁体   English

将dataTable中的数据保存到数据库

[英]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.如何将我所有的数据表数据保存到我的数据库中?,我使用 jquery 和 php 来做这个动态。

        $('#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.这是我必须从数据表中发布数据的内容,但我不知道为什么要发送到将插入的 php 函数的函数。

You can consume the data object sent from your AJAX call as POST parameters or query string parameters depending on your settings.根据您的设置,您可以使用从 AJAX 调用发送的数据对象作为 POST 参数或查询字符串参数。 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:现在,连接到您的数据库并通过您的 php 脚本插入此数据:

$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.您的回调函数将包含从 php 文件发回的数据。 Since we are sending back a json string, we can make an object of it like this:由于我们发送回一个 json 字符串,我们可以像这样创建一个对象:

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!我希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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