dongxidui1227 2012-12-20 02:15
浏览 32
已采纳

运行插入查询抓取ID并使用Id更新另一个表

I need to insert a new row in to a table, then grab the ID of that row and update another table. This is what I have:

$leadSQL="INSERT INTO $leadsTable (leadName, leadStatus, leadDescription, leadOpportunity, leadSource, leadSourceDescription, id, leadSince, contactID)
                     VALUES ('$_POST[leadName]', '$_POST[leadStatus]', '$_POST[leadDescription]', '$_POST[leadOpportunity]', '$_POST[leadSource]', '$_POST[leadSourceDescription]','$_POST[id]','$leadSince','$_POST[contactID]')";
$leadQuery = mysql_query($leadSQL);
$lastLeadID = mysql_insert_id();
$updateContactSQL = "UPDATE $contactsTable SET leadID = $lastLeadID WHERE contactID = $_POST[contactID]";
$updateContactQuery = mysql_query($updateContactSQL);

Everything works fine.. except that it inserts duplicate rows into the leads table. I have tried putting the update query into an if statement and it did the samething(this was just to try "something"). If I remove $lastID = mysql_insert_id(); it inserts just one row but obviously does not update the contacts table. So I am pretty sure it has to to with mysql_insert_id(). I need it to update the contacts table with the new id of the row inserted into the leads table. Any ideas would be greatly appreciated.

  • 写回答

1条回答 默认 最新

  • dongyue110702 2012-12-20 02:38
    关注

    for all intents and purposes what you have should work.

    you might try trimming the fat a little bit though. Since you don't need a resource for your query (it's an INSERT), you can get rid of that variable. And I'd just put the mysql_insert_id() in your update statement.

    like this:

    $leadSQL="INSERT INTO $leadsTable (leadName, leadStatus, leadDescription, leadOpportunity, leadSource, leadSourceDescription, id, leadSince, contactID)
                         VALUES ('$_POST[leadName]', '$_POST[leadStatus]', '$_POST[leadDescription]', '$_POST[leadOpportunity]', '$_POST[leadSource]', '$_POST[leadSourceDescription]','$_POST[id]','$leadSince','$_POST[contactID]')";
    mysql_query($leadSQL);
    $updateContactSQL = "UPDATE $contactsTable SET leadID = '".mysql_insert_id()."' WHERE contactID = $_POST[contactID]";
    mysql_query($updateContactSQL);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写