I have a problem with my PHP and MySQL code. I was creating a private messaging system but unfortunately, each time I reload the page, the last message sent is duplicated in the database and then displayed twice, three times and so on. I tried to put conditions before the insertion command in the database but it still does not work. I put at your disposal the part of the code which is problematic as well as a screenshot of what happens in the web page after the reloading of it.
Code that insert the message into the BDD :
<?php
session_start();
$bdd = new PDO('mysql:host=127.0.0.1;dbname=myanime', 'root', ''); //connexion a la bdd(base de donnée)...
$recup_id = $bdd->prepare("SELECT * FROM myanime_follow WHERE id_follow = ?");
$recup_id->execute(array($_SESSION["id"]));
if(isset($_POST["envoie"])){
if(isset($_SESSION["id"], $_GET["id_following"]) AND !empty($_SESSION["id"]) AND !empty($_GET["id_following"])){
$id_following = urldecode(intval($_GET["id_following"]));
if(isset($_POST["message"]) AND !empty($_POST["message"])){
$lu = 0;
$message = htmlspecialchars($_POST["message"]);
$sending = $bdd->prepare("INSERT INTO myanime_message(id_expediteur, id_destinataire, messages, lu) VALUES(?, ?, ?, ?)");
$sending->execute(array($_SESSION["id"], $id_following, $message, $lu));
}else{
$erreur = "vous devez envoyer du texte pour l'envoyer";
}
}
}
if(isset($erreur)){
echo $erreur;
}
Code that show the message to the user :
<?php
while($id_following = $recup_id->fetch()){
$id_pseudo = $bdd->prepare("SELECT * FROM myanime_membre WHERE id = ?");
$id_pseudo->execute(array($id_following["id_following"]));
if($id_pseudo->rowCount() == 1){
$pseudo = $id_pseudo->fetch();
if(isset($pseudo["pseudo"])){
?>
</br><a href="MyAnime_Messagerie.php?id_following=<?= urlencode($id_following["id_following"])?>">-><?= $pseudo["pseudo"]?></a></br></br>
<?php
}
}
}
if(isset($_SESSION["id"], $_GET["id_following"]) AND !empty($_SESSION["id"]) AND !empty($_GET["id_following"])){
$id_following = urldecode(intval($_GET["id_following"]));
$compte_principale = $bdd->prepare("SELECT * FROM myanime_membre WHERE id = ?");
$compte_principale->execute(array($_SESSION["id"]));
$pseudo_principale = $compte_principale->fetch();
$message = $bdd->prepare("SELECT * FROM myanime_message WHERE id_expediteur = ? AND id_destinataire = ? OR id_expediteur = ? AND id_destinataire = ? ORDER BY id");
$message->execute(array($_SESSION["id"], $id_following, $id_following, $_SESSION["id"]));
while($recup = $message->fetch()){
if($recup["id_expediteur"] == $_SESSION["id"]){
?>
<p class="destinataire"><?= $pseudo_principale["pseudo"].": ".$recup["messages"]?></br></p>
<?php
}else{
?>
<p class="expediteur"><?= $pseudo["pseudo"].": ".$recup["messages"]?></br></p>
<?php
}
}
}else{
$erreur = "erreur de connexion";
}