我有一個main_list在MySQL中的表,我想拷貝一個特定的行到另一個my_list表。目前我正在使用DataTables,在第四列中有一個「添加」按鈕。如何使用Jquery和PHP將行復制到MySQL中的另一個表中?
JS文件:
$(document).ready(function() {
var dataTable = $('#items').DataTable({
"processing": true,
"serverSide": true,
"ajax":{
url :"items-data.php", // json datasource
type: "post", // method , by default get
error: function(){ // error handling
$(".items-grid-error").html("");
$("#items-grid").append('<tbody class="items-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
$("#items-grid_processing").css("display","none");
}
},
"columnDefs": [ {
"targets": 0,
"data": null ,
"render": function (data) {
return '<a href=//'+data[ 3 ]+' target="_blank">'+data[ 0 ]+'</a>';
}
},
{ "visible": false, "targets": [ 3 ] },
{ "sClass": "add", "targets": [ 4 ] },
{
"targets": -1,
"data": null,
"defaultContent": "<button>Add</button>"
} ]
});
$('#items-grid tbody').on('click', 'button', function (e) {
e.preventDefault();
var myData = 'addToList';
jQuery.ajax({
type: "POST",
url: "add.php",
dataType:"text",
data:myData,
success:function(response){
alert('Success');
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
});
所以我想不出什麼樣的數據,我應該通過AJAX POST發送這樣我就可以觸發MySQL查詢。理想情況下,我應該從MySQL表中獲得行ID。我怎樣才能做到這一點?任何幫助,將不勝感激。
PHP腳本:
<?php
//include db configuration file
include_once("connection.php");
// add item to my list
if(isset($_POST['addToList'])){
$sql = " INSERT INTO my_list (item_name, item_detail, item_location, item_website) ";
$sql.= " SELECT item_name, item_detail, item_location, item_website ";
$sql.= " FROM main_list ";
$sql.= " WHERE id = 20 ";
if (mysqli_query($conn, $sql)) {
echo "Record copied successfully";
} else {
echo "Error copying record: " . mysqli_error($conn);
}
}
?>
通過ajax發送數據庫錶行的id。 – Tyr
在兩張不同的表格中有完全相同的數據真的很必要嗎? – e4c5
我想在以後建立一個收藏夾系統,但我想一次只採取一步。目標是用戶將點擊添加按鈕並將該行復制到他的列表中。 – starfx