0

In my database project there is a form where the user will fill in to add more data to the stock. I have 4 tables in my database. During the submit of the form the if the user fills in a primary key that is already there there will have a mysqli_error()and it will state that the user has entered invalid data. But currently my lines of code has an order (please ignore that the values are not in english)

The lines below are to insert data into my first table and if there is a error it would come out as an error

$datastok = mysqli_query($connection,"INSERT into stok (Kod_Barang, Kod_Rak, Harga, Tarikh_Jual) VALUES ('$Kod_Barang','$Kod_Rak','$Harga','$Tarikh_Jual')")or die(mysqli_error());

The lines below are to insert data into my second table and if there is a error it would come out as an error

$databarang = mysqli_query($connection,"INSERT into barang (Kod_Barang, Nama_Barang, Bil_Barang) VALUES ('$Kod_Barang','$Nama_Barang','$Bil_Barang')")or die(mysqli_error());

The lines below are to insert data into my third table and if there is a error it would come out as an error

$datalokasi = mysqli_query($connection,"INSERT into lokasi (Kod_Rak, Jenis_Barang) VALUES ('$Kod_Rak', '$Jenis_Barang')")or die(mysqli_error());

The lines below are to insert data into my forth table and if there is a error it would come out as an error

$datatarikh = mysqli_query($connection,"INSERT into tarikh (Nama_Barang, Tarikh_Beli) VALUES ('$Nama_Barang', '$Tarikh_Beli')")or die(mysqli_error());

I am trying to make it so if any of the mysqli_query() fails all of it wont insert.

example of whats happening now:

$datastok runs perfectly

$databarang also runs perfectly

$datalokasi has an error and the mysqli_error() will stop it here and $datatarikh wont run .

So in this situation i would like that all $datastok $databarang $datatarikh will not execute if $datalokasi fails.

MichaelSWS
  • 25
  • 8
  • 2
    Try to use mysql transactions: https://dev.mysql.com/doc/refman/8.0/en/commit.html – ivion Mar 30 '19 at 08:45
  • The thing you need is a Transaction. https://stackoverflow.com/questions/12091971/how-to-start-and-end-transaction-in-mysqli – ADyson Mar 30 '19 at 09:32

1 Answers1

1

you can use the START TRANSACTION / COMMIT

first start with

mysqli_query($connection,"START TRANSACTION;");

and then run all your quesries without the or die()

after all queries run, check if there are any errors in one of them,

if there are no erros then COMMIT

mysqli_query($connection,"COMMIT;");

if there are errors so ROLLBACK

mysqli_query($connection,"ROLLBACK;");
shushu304
  • 1,506
  • 1
  • 7
  • 15