I'm trying to insert data into tbl_stock and at the same time update tbl_product. I have so far written an ajax code below:
<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>
which calls stock-in.php and contains the following SQL codes below
<?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();
}
}
?>
debug window shows values
The insert is not working and no error is displayed. I have spent a sleepless night trying to find out why. please I will appreciate your help.
$insert->execute();and thenif($insert){. This is wrong, the methodexecute()returns a boolean, you need to get its return value instead :$stmt = $insert->execute();if($stmt){if($_SESSION['useremail']=="" OR $_SESSION['role']=="Admin"){did you callsession_start();somewhere?window.location.reload();?