Reputation: 145
I have no idea how to make "plus / minus" rating to the correct record, I tried to do this in while loop, which shows all the records, but it's rating only the first record. How to refer to correct record? I'm newbie in PHP. Here's my code:
if (isset($_GET['najstarsze']))
{
$sql = "SELECT * FROM wpisy ORDER BY id";
}
else
{
$sql = "SELECT * FROM wpisy ORDER BY id DESC";
}
$stmt = $db->query($sql);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0){
while($row = $stmt->fetch()){
echo "
<div class='data'>
".$row['data']."
</div><br>
<div class='daneautora'>
<b>Ocena: </b>".$row['ocena']."<br>
<b>Nr: </b>".$row['id']."<br>
<b>Nick: </b>".$row['nick']."<br>
<b>E-mail: </b>".$row['email']."<br>
<b>Wpis: </b><br></div>
<div class='suchar'>
<p>
".$row['tresc']."
</p>
</div>
<div class='ocena'>
<p><a href='index.php?plus=true'>+</a> <a href='index.php?minus=true'>-</a></p>
</div>
<hr>
";
if (isset($_GET['plus']))
{
$sql = "UPDATE wpisy SET ocena = ocena + 1 WHERE id = ".$row['id']."";
$stmt = $db->query($sql);
$stmt->execute();
}
else
{
if (isset($_GET['minus']))
{
$sql = "UPDATE wpisy SET ocena = ocena - 1 WHERE id = ".$row['id']."";
$stmt = $db->query($sql);
$stmt->execute();
}
}
}
}
Upvotes: 1
Views: 32
Reputation: 23880
You need to update the link so it has a reference to the record you want to update. Try:
index.php?plus=true&id=' . $row['id']
You also probably want to update the isset
to include this new parameter as well.
if (isset($_GET['plus'], $_GET['id']))
Then you need to use prepared statements with parameterized queries so you aren't susceptible to SQL injections. Here's an example:
$sql = "UPDATE wpisy SET ocena = ocena + 1 WHERE id = ?";
$stmt = $db->prepare($sql);
$stmt->execute(array($_GET['id']));
Also when using query()
you don't need execute()
, that executes as well. The execute
is to execute a prepared statement.
PDOStatement::execute — Executes a prepared statement
-http://php.net/manual/en/pdostatement.execute.php
Upvotes: 2
Reputation: 1055
if (isset($_GET['plus']))...
) outside while
blockThere is nice PDO tutorial
Upvotes: 0