M
M
maryaturova2021-04-08 16:57:58
PHP
maryaturova, 2021-04-08 16:57:58

How to swap with one query in sql table?

With this code in a loop, I add to the array and update the value in the column

include ("bd.php");
    
    mysqli_query($db,"DELETE FROM `pictures` WHERE (`date` < DATE_SUB(NOW(),INTERVAL 1 MINUTE))");
    
    $response = [];
    $count = 1;
    $result = mysqli_query(
      $db,"SELECT `set_json`,`hash` FROM `pictures` WHERE `result`='WAITING'"
      );
      
    while ($row = mysqli_fetch_array($result)) {
      $response[$count]= json_encode(unserialize($row[0]));
      $count +=1;
      mysqli_query ($db,"UPDATE `pictures` SET `result`='PROCESS' WHERE `hash`='$row[1]'");
    }
    echo json_encode($response);

Are there options to do without enumeration?
Or maybe you can change the values ​​​​in all columns with one request?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
nokimaro, 2021-04-08
@maryaturova

//..

$hash_list = [];

while ($row = mysqli_fetch_array($result)) {
      $response[$count]= json_encode(unserialize($row[0]));
      $count +=1;

      //собираем все hash в один список
      $hash_list[] = $row[1]; 
}

//апдейтим все pictures по списку hash одним запросом
if(!empty($hash_list)) {
    mysqli_query ($db, "
        UPDATE `pictures` SET `result`='PROCESS' 
        WHERE `hash` IN('".join("','", $hash_list)."') 
    ");
}

echo json_encode($response);

V
vitaly_74, 2021-04-08
@vitaly_74

Try to use the IN keyword and substitute an array there,
for example:

SELECT *
  FROM contacts
 WHERE last_name = 'Bernard'
    OR last_name = 'Boy'
    OR last_name = 'Tomas';

became
MySQL
SELECT *
  FROM contacts
 WHERE last_name IN ('Bernard', 'Boy', 'Tomas');

In fact, when iterating, you do the same thing.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question