Mysql
 SQL >> Datenbank >  >> RDS >> Mysql

Eine Junction-Tabelle mit neuen Werten synchron halten

Dieser Thread ist alt, doch da er bei Google gut rankt und ich eine Weile brauchte, um es aufzuspüren, hier, was funktioniert hat. Ich ging von folgendem Snippet aus und passte es an:

INSERT IGNORE INTO my_table VALUES (1,1), (1,2), (1,3); DELETE FROM my_table WHERE c1 NOT IN (1,2,3) AND my_table = 1; 

Herkunft des Quellcodes: https://borzacchiello.it/how-to-update-a-junction-table/

Hier meine eigene Version, verdrahtet für PHP-Variablen in einer PDO-Schleife:

 $a_id = $my_main_id //this would be c1 in the above question //Set Variable From Post $var_1 = isset($_POST['var_1']) ? $_POST['var_1'] : ''; $var_2 = isset($_POST['var_2']) ? $_POST['var_2'] : ''; //etc, etc, etc //put variables into array $data = array('var_1'=>$var_1, 'var_2'=>$var_2, 'var_3'=>$var_3, 'var_4'=>$var_4, 'tarp_5'=>$tarp_5); //get count of variable that contain data and not empty $data_array_count = 0; foreach ($data as $column => $value) { if($value != '') { $data_array_count = ++$data_array_count; } } //if contains atleast one variable run update code if($data_array_count != 0) { //loops through and inserts each varible in array foreach ($data as $column => $value) { //ignores variables without any data if($value != '') { $insert = $db->prepare("INSERT IGNORE my_table (a_id, b_id) VALUES (:a_id, :b_id)"); $insert->execute(array(':a_id' => $a_id, ':b_id' => $value )); } } //sets up variables in array to remove any records that need to be deleted $columns = ""; $holders = ""; foreach ($data as $column => $value) { if($value != '') { $columns .= ($columns == "") ? "" : ", "; $columns .= $column; $holders .= ($holders == "") ? "" : ", "; $holders .= ":$column"; } } $delete = $db->prepare("DELETE FROM my_table WHERE accessory_id NOT IN ($holders) AND (carrier_id = :a_id)"); //bind value for main id $delete->bindValue(":a_id", $a_id); //loop to bind value for each variable stored in array with data foreach($data as $placeholder => $value) { if($value != '') { $delete->bindValue(":" . $placeholder, $value); } } $delete->execute(); } 

Angewendet auf das ursprüngliche Beispiel würden Sie diesen Code einmal für jede c1-ID ausführen, die Sie auffrischen wollen. Dieser c1-Wert entspricht der Variable $a_id in meiner Version.

Sicherheitshinweis: Prüfen Sie die Eingaben, bevor Sie sie in dynamisch gebaute DELETE-Statements einsetzen, und validieren Sie $data-Werte auf Typ und Länge.