Home  >  Q&A  >  body text

Array - php+mysql one-time update?

Assume that the member information is retrieved from the database
The member has a field, assuming it is called p
The p of each member will have a value
I want to make a project where I can "get the p of all members at once Modify the value"
How should I handle my php backend? !

代言代言2709 days ago776

reply all(5)I'll reply

  • 漂亮男人

    漂亮男人2017-06-12 09:21:49

    First write an array to store the member ID and modify the p value

    $vips = array(
        array(
            'id' => 1,
            'p' => 1
        ),
        array(
            'id' => 2,
            'p' => 2
        ),
        ...
    );
    foreach ($vips as $vip) {
        执行sql语句 update 会员表 set p  = $vip['p'] where id = $vip['id'];
    }

    reply
    0
  • 欧阳克

    欧阳克2017-06-12 09:21:49

    The solution currently adopted by @tony_yin is the most basic solution. In actual applications, attention should be paid to enabling the transaction before the for loop starts and submitting the transaction after it ends. Otherwise, not to mention low performance, if there is a problem with the program during the for loop, it is easy to cause only some of the users' p values ​​to be updated, while the other parts are not.

    I will add another solution here: since it is mysql, you can use INSERT ... ON DUPLICATE KEY UPDATE to batch update. Sample SQL:

    INSERT INTO `user`
     ( `id`, `p` ) 
    VALUES
     ( 11111, 1),
     ( 22222, 2),
     -- ...
     ( 99999, 9)
    ON DUPLICATE KEY UPDATE
      `id` = VALUES(`id`),
      `p` = VALUES(`p`);

    reply
    0
  • PHP中文网

    PHP中文网2017-06-12 09:21:49

    update 会员表 set p = xxx

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-06-12 09:21:49

    Find out the member’s ID and modify it once.
    If the amount of data is large, process it in batches

    update table set p = value where uid in(1,2,3)
    1. It doesn’t matter if the amount of data is small and it can be placed in a loop

    2. Depending on your own needs

    reply
    0
  • 世界只因有你

    世界只因有你2017-06-12 09:21:49

    I didn’t understand your question. Please describe it clearly when I ask. Otherwise it will be a rubbish question.
    I think you want to ask some members to set their p fields at once, right?
    `
    update table set p = value where uid in(1,2,3)
    `

    Write the following where condition yourself according to the specific scenario

    Or you’d better re-describe your problem

    reply
    0
  • Cancelreply