<?php
$sql = mysqli_query($bdd,"SELECT * FROM ".$prefix."_savoirsmaj WHERE niveau = '".$divdeb."e'");
$sx = mysqli_query($bdd,"SELECT * FROM ".$prefix."_savoirs".$divdeb." WHERE s".$divdeb."_id LIKE 'PER%'");
if(mysqli_num_rows($sql)>0) {
	foreach($sql as $sql_info) {
		$att0 = mysqli_real_escape_string($bdd,$sql_info['s_id']);
		$att1 = mysqli_real_escape_string($bdd,$sql_info['nom_savoir']);
		$att2 = mysqli_real_escape_string($bdd,$sql_info['niveau']);
		$att3 = mysqli_real_escape_string($bdd,$sql_info['champs_id']);
		$att4 = mysqli_real_escape_string($bdd,$sql_info['notions']);
		$att5 = mysqli_real_escape_string($bdd,$sql_info['base']);
		// ajout quand le savoir n'existe pas déjà
		$s = mysqli_query($bdd,"SELECT * FROM ".$prefix."_savoirs".$divdeb." WHERE s".$divdeb."_id='".$att0."'");
		$s_nb = mysqli_num_rows($s);
		if($s_nb == 0)
		{
			mysqli_query($bdd,"INSERT INTO ".$prefix."_savoirs".$divdeb." (s".$divdeb."_id, nom_savoir, niveau, champs_id, notions, base) VALUES ('" . $att0 . "', '" . $att1 . "', '" . $att2 . "', '" . $att3 . "', '" . $att4 . "', '" . $att5 . "')");
		}
		else {
			// on update le savoir
			mysqli_query($bdd,"UPDATE ".$prefix."_savoirs".$divdeb." SET nom_savoir='".$att1."', niveau='".$att2."', champs_id='".$att3."', notions='".$att4."', base='".$att5."' WHERE s".$divdeb."_id='".$att0."'");
		}
	}
}

// 3. Suppression (delete) quand la ligne n'existe que dans savoirs*
if(mysqli_num_rows($sx)>0) {
	foreach($sx as $sx_info) {
		$sid = $sx_info['s'.$divdeb.'_id'];
		$snew = mysqli_query($bdd,"SELECT * FROM ".$prefix."_savoirsmaj WHERE s_id='".$sid."'");
		$snew_nb = mysqli_num_rows($snew);
		
		if($snew_nb == 0)
		{
			// on supprime le savoir
			$savtosup = mysqli_query($bdd,"SELECT * FROM ".$prefix."_savoirs".$divdeb." WHERE s".$divdeb."_id='".$sid."'");
			$savtosup_info = mysqli_fetch_assoc($savtosup);
			$savtosup_id = $savtosup_info['s'.$divdeb.'_id'];
			
			mysqli_query($bdd,"DELETE FROM ".$prefix."_savele WHERE s_id = '".$savtosup_id."'");
			mysqli_query($bdd,"DELETE FROM ".$prefix."_savoirs".$divdeb." WHERE s".$divdeb."_id = '".$savtosup_id."'");
			mysqli_query($bdd,"DELETE FROM ".$prefix."_seqsav WHERE s_id = '".$savtosup_id."'");
		}	
	}
}
?>
