How do I update a table after clicking a button?

I’m working on a vote system, i have 2 buttons, Yes and No
I want my ‘score’ in my table to add 1 when pressed Yes
and -1 when pressed No

And i want ‘totalvoted’ to go up whatever the answer is yes or no

I have this but it’s not working:

<form action="index.php" method="post">

<input type="button" value="Yes" name="upBtn" id="upBtn" > 
<input type="button" value="No" name="downBtn" id="downBtn" > 

</form>
<?php


    if (isset($_POST['upBtn'])) {
               mysql_query("UPDATE tablename SET score = score + 1");
               mysql_query("UPDATE tablename SET totalvoted = totalvoted + 1");

            }
    if (isset($_POST['downBtn'])) {
             mysql_query("UPDATE tablename SET score = score - 1");
               mysql_query("UPDATE tablename SET totalvoted = totalvoted + 1");

            }

            print "$score[0]";
    ?>

The first thing you should know is that mysql is no longer a part of PHP, it has been removed.
You must use either mysqli or PDO to communicate with your database.

1 Like

So should this be able to make it work ?

<?php


    if (isset($_POST['upBtn'])) {
               mysqli_query($conn,"INSERT INTO tablename (score,totalvoted) 
VALUES ('+1','+1')");

            }
    if (isset($_POST['downBtn'])) {
             mysqli_query($conn,"INSERT INTO tablename (score,totalvoted) 
VALUES ('-1','+1')");

            }

            print "$score[0]";
    ?>

Didn’t you try it?

You seem to have changed the queries quite substantially from your first code example. I suspect these newer queries will do nothing other than insert some rows containing strings into your database, or perhaps return an error, depending on the structure of the table.

The problem with the queries in your first code (and in the second too) is that they don’t specify which rows in the table are to be updated. If you only have one row, or if you want to update all rows, that’s fine of course.

On this line:

 print "$score[0]";

Where is this coming from? Do you set it in a bit of code that you didn’t post?

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.