简体   繁体   中英

PHP run SQL result in another SQL statement

Is this possible? I need to run the result of one sql statement into another..

$result= mysqli_query($dbconn,"Select max(cartid) from cart;");
$row = mysqli_fetch_assoc($result);

$sql1 = "insert into cart(cartid) values('".$row['max(cartid)']."');";
mysqli_query($dbconn,$mysql1);

EDIT:

Added in my sql tables to show a better example of what im trying to do This is my cart table 在此处输入图片说明

This is my transaction table 在此处输入图片说明

Basically I want to transfer the row where cartid = 5 from cart table, into the transaction table where the new transaction id will be = 5. As you can see, the transaction table also has a cartid. Not sure how im going to bring over this cartid and insert into the transaction table as a new row. FYI, in order to get cartid=5 i would like to use order by cartid desc limit 1 to get the last possible row in the cart table

The new transaction table's row will look something like this.

transactionid outletid nric cartid transactiondate totalbeforediscount totalafterdiscount transactiontime username
     5           0      0     5         0                 0                       0                 0            0

You can combine the queries into one.

Please give it a try:

INSERT INTO cart(cartid) SELECT MAX(cartid) FROM cart

WORKING DEMO

EDIT:

In order to insert mulitiple values like that your query would look like below:

INSERT INTO cart(cartid,rowid) SELECT MAX(cartid),MAX(rowid) FROM cart

WORKING DEMO

But I don't understand why are trying to insert the columns having max value in the same table. Since your table contains those already.

Edit2:

INSERT INTO transaction_table(cartid) SELECT MAX(cartid) FROM cart;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM