我在 MySQL 中有一个 main_list 表,我想将特定行复制到另一个 my_list 表。目前我正在使用数据表,在我的第 4 列中有一个“添加”按钮。
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);
}
}
?>
最佳答案
首先要做的是简化问题。这不一定是 jquery/php 组合问题。您可以先对执行数据库查询的 PHP 代码进行操作。您可以通过在 URL 中传入不同的参数来直观地测试它。一旦你让它工作,将那个 url 插入你的 javascript 代码以让它们一起工作是一件微不足道的事情。
url参数可以是记录的主键。您现在已经对其进行了硬编码 $sql.= "WHERE id = 20 ";
它应该将其更改为 $sql.= "WHERE id = 20 ";
它的值(value)来自于 $_POST
关于php - 如何使用 Jquery 和 PHP 将行复制到 MySQL 中的另一个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32023789/