我一直在尝试退回一美元wpdb->;插入\\u id;但不幸的是,它正在返回null;我做错了什么?我使用ajax从前端发送数据。这是后端代码。
function add_fav() {
global $wpdb;
$table = $wpdb->prefix . "fav_products";
$productID = (int) $_POST[\'product_id\'];
$response = [];
$insertid = 3;
if(isset($_POST[\'amount\'])) {
$amount = (int) $_POST[\'amount\'];
}
else{
$amount = 1;
}
if(isset($_COOKIE[\'fav_id\']) && !empty($_COOKIE[\'fav_id\']))
{
$fav_id = $_COOKIE[\'fav_id\'];
}
else
{
$fav_id = uniqid();
setcookie(\'fav_id\', $fav_id, strtotime(\'+1 year\'), \'/\');
}
$itemInfav = $wpdb->get_row($wpdb->prepare("SELECT id, fav_id, product_id FROM $table WHERE fav_id = %s AND product_id = %d", $fav_id, $productID));
if(!empty($itemInfav->product_id))
{
$response[\'sorry\'] = "Sorry the product already exist in Wishlist!";
}
else
{
// insert
$toevoegen = $wpdb->insert(
$table,
array(
\'fav_id\' => $fav_id,
\'product_id\' => $productID,
\'amount\' => $amount,
),
array(
\'%s\',
\'%d\',
\'%d\'
)
);
$lastinsertid = $toevoegen->insert_id;
}
$totalInfav = $wpdb->get_row($wpdb->prepare("SELECT SUM(AMOUNT) as total FROM $table WHERE fav_id = %s", $fav_id));
$response[\'result\'] = $toevoegen;
$response[\'fav_id\'] = $fav_id;
$response[\'total\'] = $totalInfav->total;
$response[\'insertid\'] = $lastinsertid;
wp_send_json( $response );
wp_die();
}
下面是我的数据库结构。我确实有外键在里面。
CREATE TABLE $favtable (
id int(11) NOT NULL AUTO_INCREMENT,
product_id int(11) NOT NULL,
fav_id varchar(255) NOT NULL,
amount int(11) NOT NULL,
created_at timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
这就是前端ajax的外观。
$(\'body\').on(\'click\', \'.addToFav\', function(e)
{
e.preventDefault();
var product_id = $(this).data(\'product-id\'),
ajax = $(this).data(\'ajax\'),
siteurl = $(this).data(\'url\'),
uid = $(this).data(\'uid\'),
$image = $(\'.\'+uid).children(\'img\'),
img = document.createElement("img");
img.src = siteurl+\'/wp-content/themes/bg/assets/images/favorite-icon-white.svg\',
$.post(ajax, {
action: \'add_fav\',
product_id: product_id},
function(data){
console.log(data);
updateFavIcon(parseInt(data.total));
if( data.result ) {
console.log(data.insertid);
$(\'.\'+uid).removeClass(\'addToFav\');
$(\'.\'+uid).addClass(\'addedFav\');
$image.remove();
$(\'.\'+uid).append(img);
$(\'.\'+uid).data(\'wid\', data.insertid);
$(\'.\'+uid).attr(\'data-wid\', data.insertid);
}
});
});
谁能帮我找出我做错了什么,最后一个插入id没有返回?提前谢谢。