There are two identical tables: data_tmp and data which have one entry each.

Is it possible to somehow copy all the data from data_tmp and data in one request? Essentially select all the data data_tmp and make an update in the data?

Since there are so many columns with tables, it is inconvenient to make 2 queries.

2 answers 2

Try this

$result = mysqli_query($db, 'SELECT с1 ,с2 FROM data_tmp ') or die('error! Записей не найдено!'); while ($rows=mysqli_fetch_row($result)){ mysqli_query($db, "INSERT INTO data (p1 ,p2) VALUES( '".$rows[0]."','".$rows[1]."')")or die("Ошибка…". mysql_error()); } 
  • In mysqli_query, $ db should be like the first argument. - Yuri
  • Well, this is an example of the classic method of two queries, the question was how to manage with one query, without re-counting the slobbles, if possible. - Yuri
  • @ Yuri corrected, thank you - TimurVI
  • @Yury, in my understanding, you need to sort through the lines, I don’t imagine without a cycle. And yet it will be interesting for me to observe the solution of your question. - TimurVI
  • In the cycle there is no need, since the table has one line, simple copying of statistics. but many columns ... - Yuri

If the order of the fields is identical, then everything is done in one request.

 INSERT INTO data SELECT * FROM data_tmp 

but it is not strongly recommended to do so, because when changing the order of the fields, you will have porridge without any messages.

What is the problem to get a list of fields (at least to score), and then create a query

 $fields = 'fld1, fld2, fldn'; $sql = sprintf('INSERT INTO data (%s) SELECT %s FROM data_tmp', $fields, $fields); 

Or execute the query

 SELECT * FROM data_tmp 

and then, based on mysqli_stmt_result_metadata, find out the field names and form an INSERT request?

UPDATE

If you need to update the records, then you need to add the construction ON DUPLICATE KEY UPDATE but then the fields will have to be listed. But again, having a list of fields doesn't cost anything.

 function upd($val) { return sprintf('$s = VALUES(%s)', $val, $val); } $fields = 'fld1, fld2, fldn'; $fld_upd = explode(',', $fields); $fld_upd = array_map('upd', $fld_upd); $fld_upd = implode($fld_upd); $sql = sprintf( 'INSERT INTO data (%s) SELECT %s FROM data_tmp ON DUPLICATE KEY UPDATE %s', $fields, $fields, $fld_upd ); 
  • As far as I understand, INSERT will add a new record, but you need to update the existing one from data_tmp in data. - Yuri
  • @ Yuri Added solution with update - Anton Shchyrov