(This guide assumes you have the basic knowledge of HTML, PHP and MySQL.)
1. Use PHP to connect to the database.
<?php
$db = mysqli_connect('localhost','root','','media') //root is the username and no password.
or die('Error connecting to MySQL server.');
?>
Here, 'media' is the database name and it is running on WAMP.
2. Use a while loop to fetch contents from the database.
For each entry add a Button.
<form method="POST">
<?php
$query = "SELECT * FROM post";
mysqli_query($db, $query) or die('Error querying database.');
$result = mysqli_query($db, $query);
while ($row = mysqli_fetch_array($result)) {
$varid=$row['postID'];
echo '<br><br><h5>Name: '.$row['name'].'<br>'. $row['agree'];
?>
<form method="post">
<div>
<input type="submit" name="<?php echo $varid; ?>" value="Agree">
</div>
</form>
Note: Each button must have a different name so that it will have a different functionality. For simplicity, we will give the id(primary key) of the row in the database as the name of that button. Which is why the name attribute has a php in its value. Also note that the php script is closed before the form tag.
Value of varid is taken from the row fetched from the database where post is the table name and postID is the primary key.
3. Then, we add the function of every button.
<?php
echo '<hr>';
if(isset($_POST[$varid])){
$qry1="update post set agree=agree+1 where postID='$varid';";
mysqli_query($db,$qry1);
header("Refresh:0");
}
}
mysqli_close($db);
?>
4. Enclose the code within HTML body.
The entire code:
And here is the output:
Comments
Post a Comment