登录 | 注册 | FAQ
Anonymous

make a multi task query

+ 发表回复

5 篇帖子 分页: 1 / 1


make a multi task query

amanpoke » 周三 7月 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.
头像

amanpoke

  • 帖子: 85
  • 注册: 周六 2月 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

amanpoke » 周四 7月 31, 2014 2:13 am

The query I made :


代码: 全选

$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?
头像

amanpoke

  • 帖子: 85
  • 注册: 周六 2月 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

XainPro » 周四 7月 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
头像

XainPro

  • 帖子: 3933
  • 注册: 周五 2月 17, 2012 8:10 pm

Re: make a multi task query

amanpoke » 周四 7月 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.
头像

amanpoke

  • 帖子: 85
  • 注册: 周六 2月 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

XainPro » 周日 8月 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 :)
头像

XainPro

  • 帖子: 3933
  • 注册: 周五 2月 17, 2012 8:10 pm


+ 发表回复

分页: 1 / 1