PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 23, 2022

[FIXED] How to update a table with a foreach without overwriting?

 October 23, 2022     foreach, overwrite, php, sql, sql-update     No comments   

Issue

So i'm working on a university project but i have a problem that's really starting to bother me. I am trying to update my database several times with different values, except that only the last value will be taken into account : they're overwriting themselves.

My code :

$id_structure = $_POST['id_structure'];
foreach ($id_structure as $id2) {
      $id_structure = explode(",", $id2);
      updateDemandeStructure($id_demande[0], $id2, 0);
}

And my SQL method is like this :

function updateDemandeStructure($id_demande, $id_structure, $principale) {
    global $bd;
    $stmt = $bd->prepare('UPDATE demandes_structures SET id_structure = :id_structure, principale = :principale WHERE id_demande = :id_demande');
    $stmt->bindParam(ID_DEMANDE, $id_demande);
    $stmt->bindParam(ID_STRUCTURE, $id_structure);
    $stmt->bindParam(':principale', $principale);
    $stmt->execute();
}

So for example if I (id_demande = 1) choose 4 new structures with their id_structure : 22,23,24,25, I'm going to have my table who looks like :

ID_DEMANDE ID_STRUCTURE PRINCIPALE
1 25 0
1 25 0
1 25 0
1 25 0

Please does anyone know what to modify in my code so that my table looks like this after my update?

ID_DEMANDE ID_STRUCTURE PRINCIPALE
1 22 0
1 23 0
1 24 0
1 25 0

Thank you very much!


Solution

Thanks for all of your answers, as I'm running out of time, I decided to choose @ADyson's solution :

Instead of doing like this :


foreach ($id_structure as $id2) {
      $id_structure = explode(",", $id2);
      updateDemandeStructure($id_demande[0], $id2, 0);
}

I did this :

deleteDemandeStructure($id_demande[0]);

foreach ($id_structure as $id2) {
      $id_structure = explode(",", $id2);
      addDemandeStructure($id_demande[0], $id2, 0);
}

I'll come back to you if I have time to set up a more dynamic version!



Answered By - elieeee
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing