简体   繁体   English

MySQL仅在行之前已插入的情况下更新

[英]Mysql only update if row has been inserted before

I want to only run the update query if row exists (and was inserted). 我只想在行存在(并已插入)的情况下运行更新查询。 I tried several different things but this could be a problem with how I am looping this. 我尝试了几种不同的方法,但这可能是我如何循环使用此方法的问题。 The insert which works ok and creates the record and the update should take the existing value and add it each time (10 exists + 15 added, 25 exists + 15 added, 40 exists... I tried this in the loop but it ran for every item in a list and was a huge number each time. Also the page is run each time when a link is clicked so user exits and comes back 可以正常工作并创建记录的插入,并且更新应采用现有值并将其每次添加(10存在+ 15添加,25存在+ 15添加,40存在...我在循环中尝试了此操作,但它为列表中的每个项目,每次都有很大的数目。每次单击链接时都会运行该页面,以便用户退出并返回

while($store = $SQL->fetch_array($res_sh)) 
{
$pm_row = $SQL->query("SELECT * FROM `wishlist` WHERE shopping_id='".$store['id']."'");
$myprice = $store['shprice'];
    $sql1 =  "insert into posted (uid,price) Select '$uid','$myprice'
        FROM posted WHERE NOT EXISTS (select * from `posted` WHERE `uid` = '$namearray[id]') LIMIT 1";
    $query = mysqli_query($connection,$sql1);  
}

$sql2 = "UPDATE posted SET `price` = price + '$myprice', WHERE shopping_id='".$_GET['id']."'"; 
$query = mysqli_query($connection,$sql2);

Utilizing mysqli_affected_rows on the insert query, verifying that it managed to insert, you can create a conditional for the update query. 在插入查询中使用mysqli_affected_rows ,以确认它已成功插入,您可以为更新查询创建条件。

However, if you're running an update immediately after an insert, one is led to believe it could be accomplished in the same go. 但是,如果您在插入后立即运行更新,则会导致人们相信可以同时完成更新。 In this case, with no context, you could just multiply $myprice by 2 before inserting - you may look into if you can avoid doing this. 在这种情况下,没有上下文,您可以在插入之前将$myprice乘以2-如果您可以避免这样做,可以考虑一下。

Additionally, but somewhat more complex, you could utilize SQL Transactions for this, and make sure you are exactly referencing the row you would want to update. 此外,但稍微复杂些,您可以为此使用SQL事务 ,并确保完全引用要更新的行。 If the insert failed, your update would not happen. 如果插入失败,则不会进行更新。

Granted, if you referenced the inserted row perfectly for your update then the update will not happen anyway. 当然,如果您完美地参考了插入的行以进行更新,则无论如何都不会发生更新。 For example, having a primary, auto-increment key on these rows, use mysqli_insert_id to get the last inserted ID, and updating the row with that ID. 例如,在这些行上具有主自动递增键,请使用mysqli_insert_id获取最后插入的ID,然后使用该ID更新该行。 But then this methodology can break in a high volume system, or just a random race event, which leads us right back to single queries or transaction utilization. 但是,这种方法可能会破坏大容量系统,或者只是随机竞争事件,这会使我们直接回到单个查询或事务利用率。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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