that's how I'm making my own little "like" system for my website, this is how when I click "like" then throw it all id into the database so it means that I have 1, 2 , 3, 4, and 5, so if for example, I click on 5 so smidre on all the others into the database even though I did not click on them.
so the problem is that it throws some numbers into the database which I have not looked
$sql = "SELECT bruger.fornavn, bruger.efternavn, bruger.img, wall.id, wall.tekst, wall.brugerid, wall.opret_dag FROM wall JOIN bruger ON wall.brugerid=bruger.id ORDER BY `wall`.`id` DESC";
if ($stmt = $this->mysqli->prepare($sql))
{
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($fornavn, $efternavn, $img, $id, $tekst, $brugerid, $opret_dag);
while ($stmt->fetch())
{
?>
<div class="statwall">
<h2>Test</h2>
<div class="wallindhold">
<?php
echo $tekst;
?>
</div>
<?php
if($_SESSION["login"] != false and $_SESSION["rank"] == 1)
{
?>
<form action="#" method="post">
<input type="submit" name="like" value="Synes godt om" id="likebutton">
</form>
<?php
if(isset($_POST["like"]))
{
if($stm = $this->mysqli->prepare('INSERT INTO wallLike (getid, brugerid, dato_time) VALUES (?, ?, now())' ))
{
$stm->bind_param('ss', $getid, $brugerid);
$getid = $id;
$brugerid = $_SESSION["id"];
$stm->execute();
echo "No Error!";
$stm->close();
}
else
{
echo 'Der opstod en fejl i erklæringen: ' . $this->mysqli->error;
}
}
}
?>
<div style="clear:both;"></div>
</div>
<?php
}
$stmt->close();
}
The problem is that it throws all the numbers into the database. what I want to only throw a number into the database possibly the figures that I have clicked.
Your page currently has lots of forms, but they are all exactly the same. Whichever one you click, the values you get will be the same, so the same thing will happen. You check if a form has been submitted here:
if(isset($_POST["like"]))
But there is nothing to tell which form was submitted. So if a form was submitted, that will always be true
, and the code will insert things into the database.
First, you need to make your forms different in some way. For instance, add a hidden input with the value of $id
in:
?>
<form action="#" method="post">
<input type="submit" name="like" value="Synes godt om" id="likebutton">
<input type="hidden" name="like_id" value="<?php echo $id; ?>" />
</form>
<?php
Second, you need to check which form was submitted:
if( isset($_POST["like"]) && $_POST["like_id"] == $id )
Note that you could have two completely separate loops, one displaying the forms, and one processing the database INSERT
s after the form has been submitted. This is often recommended, because it makes it clearer when different things are happening.