Hello everyone, I have a function that adds several rows to the database by taking values ​​from the array

function createQuery($id, $a, $b){ $query = "INSERT INTO opisanie (x,text,text_opis) VALUES "; $limit = count($a); for($i=0; $i<$limit; $i++){ $query .= "('{$id}','{$a[$i]}', '{$b[$i]}')".($i!=$limit-1?',':''); } $res = mysql_query($query); } $aText = $_POST['form_text_o']; $aOpis = $_POST['form_text_opis']; $query = createQuery($id, $aText, $aOpis); 

How to me the same principle to update lines in a DB? Tell me please..

  • one
    you can even take advantage of the same insert by adding ON DUPLICATE KEY UPDATE to stackoverflow.com/questions/2714587/… - Mike
  • Again mysql - poke it with a stick and rewrite it everywhere on mysqli - Gedweb
  • Give specific conditions for the selection of the updated rows, then you can set an example SQL query, - Alexus
  • @Mike thanks for the comment, all studied and compiled an answer in more detail. - Ruslan Liashenka

1 answer 1

It turned out to be quite simple, at the end I added ON DUPLICATE KEY UPDATE text = VALUES(text), text_opis = VALUES(text_opis) which meant if X - the unique key will match, then you need to update the text and text_opis tables in this row, if there are matches will not, then add a new line with the values text and text_opis . A great solution to update and add new entries at the same time.

  function createQuery($id, $a, $b){ $query = "INSERT INTO opisanie (x,text,text_opis) VALUES "; $limit = count($a); $update = "ON DUPLICATE KEY UPDATE text = VALUES(text), text_opis = VALUES(text_opis)"; for($i=0; $i<$limit; $i++){ $query .= "('{$id}','{$a[$i]}', '{$b[$i]}')".($i!=$limit-1?',':''); } $res = mysql_query($query.$update); } $aText = $_POST['form_text_o']; $aOpis = $_POST['form_text_opis']; $query = createQuery($id, $aText, $aOpis); 

Thanks @Mike for comment.