Login | Register | FAQ
Anonymous

make a multi task query

+ Post a reply

5 posts Page 1 of 1


make a multi task query

by amanpoke » Wed Jul 30, 2014 3:17 am

I was looking for a sample query in which I can first INSERT a new row.

Select the id of the inserted row. Then update that id in an another row.

I want to do it in a single query. Or in any other best practice.
User avatar

amanpoke

  • Posts: 85
  • Joined: Sat Feb 04, 2012 3:20 pm
--
Join Linkbucks and get paid to share your links:
https://www.linkbucks.com/referral/527073

Re: make a multi task query

by amanpoke » Thu Jul 31, 2014 2:13 am

The query I made :


Code: Select all

$q1 = "INSERT id,uname,pid INTO user VALUES(null,'$uname','$pid')";
mysql_query($q1);
$q2 = "SELECT id FROM user WHERE uname='$uname'";
$r = mysql_query($q2);
$id = mysql_result($r,0,'id');
$q3 = "UPDATE user SET lchild='$id' WHERE id='$pid'";
mysql_query($q3);




I want to make sure that all the 3 queries are executed.
Also I want to convert it into a single query. Is that possible?
User avatar

amanpoke

  • Posts: 85
  • Joined: Sat Feb 04, 2012 3:20 pm
--
Join Linkbucks and get paid to share your links:
https://www.linkbucks.com/referral/527073

Re: make a multi task query

by XainPro » Thu Jul 31, 2014 9:38 am

There are lot's of method of doing this but the simple and easy one would be like this

$q1 = "INSERT id,uname,pid INTO user VALUES(null,'$uname','$pid')";
mysql_query($q1);
$pid = mysql_insert_id();

$q2 = "UPDATE user SET lchild='$id' WHERE id='$pid'";
mysql_query($q2);

this can be done in 2 quires
User avatar

XainPro

  • Posts: 3933
  • Joined: Fri Feb 17, 2012 8:10 pm

Re: make a multi task query

by amanpoke » Thu Jul 31, 2014 1:37 pm

Is it possible to do it in one query coz I want to make sure that the complete sequence is executed or else no change is made.
User avatar

amanpoke

  • Posts: 85
  • Joined: Sat Feb 04, 2012 3:20 pm
--
Join Linkbucks and get paid to share your links:
https://www.linkbucks.com/referral/527073

Re: make a multi task query

by XainPro » Sun Aug 10, 2014 8:47 pm

you can use transaction for this kind of requirement

mysql_query("START TRANSACTION");

$q1 = "INSERT id,uname,pid INTO user VALUES(null,'$uname','$pid')";
mysql_query($q1);
$pid = mysql_insert_id();

$q2 = "UPDATE user SET lchild='$id' WHERE id='$pid'";
mysql_query($q2);

if ($q1 and $q2) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
}

if both execute successfully then comit else rollback :)
User avatar

XainPro

  • Posts: 3933
  • Joined: Fri Feb 17, 2012 8:10 pm


+ Post a reply

Page 1 of 1