【发布时间】:2021-03-27 21:17:24
【问题描述】:
我正在尝试将数据插入 tbl_stock 并同时更新 tbl_product。到目前为止,我已经在下面编写了一个 ajax 代码:
<script>
$(document).ready(function() {
$('#btn_stockin').click(function() {
event.preventDefault();
/*Reading value from modal*/
var newStock = $('#txt_addstock').val();
var newPrice = $('#txt_addprice').val();
if(newStock == '' && newPrice == ''){
alert("Oops!, fill Text fields and try again.");
}else{
$.ajax({
method: 'POST',
url: 'stock-in.php',
data:{stock_up: newStock, cost: newPrice,
<?php
echo 'id: "'.$row->pid.'", oldstock: "'.$row->pstock.'", productcategory: "'.$row->pcategory.'", productname: "'.$row->pname.'", currentDate : "'.$savedate.'" '
?>
},
success:function(data){
$('#add_stock_modal').modal('hide');
return data;
}
});
}
});
});
</script>
调用stock-in.php并包含以下SQL代码
<?php
include_once'connectdb.php';
if($_SESSION['useremail']=="" OR $_SESSION['role']=="Admin"){
header('location:index.php');
}
if(isset($_POST['stock_up'])){
$product_category = $_POST['productcategory'];
$product_name = $_POST['productname'];
$current_date = $_POST['currentDate'];
$stockup = (int)$_POST['stock_up'];
$newPrice = (int)$_POST['cost'];
$id = $_POST['id'];
$oldstock = (int)$_POST['oldstock'];
$new_stock = $oldstock + $stockup;
$amount_owed = $newPrice * $stockup;
try {
//your stuff
$query="insert into tbl_stock(category_name,product_name,stock_in,stock_price,total_cost,stocked_date)
values('$product_category','$product_name','$stockup','$newPrice','$amount_owed','$current_date')");
$insert=$pdo->prepare($query);
$stmt = $insert->execute();
if($stmt){
$sql="UPDATE `tbl_product` SET `pstock` = ?, `purchaseprice` = ? WHERE pid= ? ";
$update=$pdo->prepare($sql);
$update->execute([$new_stock, $newPrice, $id]);
}else{
echo'Error in updating stock';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
}
?>
【问题讨论】:
-
请注意,您的插入查询容易受到 SQL 注入的攻击。考虑使用准备好的语句,就像更新查询一样
-
$insert->execute();然后if($insert){。这是错误的,execute()returns 方法是一个布尔值,你需要获取它的返回值:$stmt = $insert->execute();if($stmt){ -
if($_SESSION['useremail']=="" OR $_SESSION['role']=="Admin"){你给session_start();打过电话吗? -
顺便问一下,如果你打电话给
window.location.reload();,那么使用AJAX有什么意义呢? -
"重新加载后刷新页面" ...但是发明 Ajax 的全部原因是为了避免刷新整个页面...相反,您应该只刷新其中的一部分,使用JavaScript 根据来自 Ajax 调用的响应更新内容。如果您只想在 Ajax 完成后立即刷新所有内容,那么您最好不要打扰...只需在一个回发请求中完成所有内容,并为您和您的用户节省额外的无意义 HTTP 请求