I would like to increment a specific entry depending on which button was clicked. The problem I am having is that I'm not sure how to tell mysql which entry to increment via php.
I'm using a while loop to display my table and then on the end of each row adding a button that has a name = $row[id] value = $row[likes]. If name was simply a word then it wouldn't be a problem but I need it to be different depending on the row it's in. (I'm using the row id the auto increments, I don't display it but it exists).
My .html: <?php // Connect to table ob_start();
$host="xxx";
$username="xxx";
$password="xxx";
$db_name="xxx";
$tbl_name="blog";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$result = mysql_query("SELECT * FROM $tbl_name ORDER BY id DESC");
echo "<table id='blog'>
<tr>
<th>Update</th>
<th>Likes</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td id='entry'>" . $row['entry'] . "</td>";
echo "<td id='like'>" . "<form action ='likes.php' method ='post'>" . "<input type='submit' name='$row[id]' value='$row[likes]' />" . "</form>" . "</td>";
echo "</tr>"; }
echo "</table>";
mysql_close($con);
?>
My .php:
<?php
$con = mysql_connect("xxx","xxx","xxx");
if (!$con) {
die('Could not connect: ' . mysql_error()); }
mysql_select_db("xxx", $con);
if(mysql_query("UPDATE blog SET likes = likes +1 WHERE id = '$_POST[$id]'")) {
header('location:blog.php'); }
else {
echo "Error: " . mysql_error(); }
mysql_close($con);
?>
All I want to do is link 'input name = $row[id]' in the html document with the WHERE id = $_POST[id] so that it will increment the like count on button click.
Use a hidden input within the form to tell the PHP side which entry to increment.
echo "<td id='like'><form action ='likes.php' method ='post'><input type='hidden' name='id' value='" . (int)$row['id'] . "' /><input type='submit' name='submit' value='" . (int)$row['likes'] . "' /></form></td>";
The query line should be:
if(mysql_query("UPDATE blog SET likes = likes +1 WHERE id = '" . (int)$_POST['id'] . "'")) {
Notice I casted the IDs as (int)
, this prevents SQL Injection in the query, and prevents XSS when outputting.
The submit button is unreliable for the transportation of data, this is because in some situations not all browsers actually send the submit button as a POST/GET variable.
The other thing I noticed was the use of this syntax $row[likes]
which should be:
$row['likes']
If you don't include quotes then PHP first treats likes
as a constant and if not defined, falls back as a string.