I have a function that is supposed to delete a product and, with it, delete its stock as well. But it keeps just deleting the stock. SSometimes I change the order of the querys and it shows an error that I can’t delete idproduto because its an FK, so I put the delete stock query first. It deletes the stock and there’s no error, but it doesn’t delete the product.
Database:
TABLE produtos(idproduto, descr) TABLE stock(idstock, idproduto, stock)
Code:
x
function removeProduto($idproduto){
global $conn;
$res="";
$sql = "DELETE FROM stock WHERE idproduto= ".$idproduto.";";
if($conn -> query($sql) === TRUE){
$sql = "DELETE FROM produtos WHERE idproduto= ".$idproduto.";";
$res = "Produto removido com sucesso";
} else {
$res = "Erro: ".$conn->error;
}
return($res);
}
I also tried to put the delete produtos query right under the other, I switched them….
Advertisement
Answer
You can use left join
DELETE s,p FROM stock s
LEFT JOIN produtos p ON s.idproduto = p.idproduto
WHERE idproduto = idproduto