Search code examples
phpmysqlmysqliadditionsubtraction

PHP MySQL maths update value in database


So ive got a rating system in place on a website im making. Currently each itema has a plus and minus button on either side as well as a visible rating level in this case its 3.1 for one of the items.

Im trying to programme both the plus and minus buttons in such a way that when the user presses them then the rating either increases or decreases by one.

Currently ive only implemented the minus button, however, when I click it the rating value doesnt decrease. It stays at 3.1. The page works fine and when i click on the "minus" button i get the error Call to a member function execute() on a non-object on line 67 which is the $stmt->execute()

Here is the code i have so far:

<?php
$results = $mysqli->query("SELECT * FROM programmes ORDER BY ProgrammeName ASC");
if ($results) { 
     $i=0;
     echo '<table><tr>';

     echo '<br/>';
     echo '<br/>';

     while($obj = $results->fetch_object())
    {   
        echo '<td>';
        echo '<div class="tvProgs">'; 
        echo '<form method="post" id = "programmes" action="">';
        echo "<input type=\"hidden\" name=\"progID\" value=\"".htmlentities($obj->ProgrammeID)."\" />";
        echo '<div class="progImage"><img src="images/'.$obj->Image.'"></div>';
        echo '<div class="progTitle"><h3>'.$obj->ProgrammeName.'</h3>';
        echo '<div class="progRating"><h5>'.$obj->Rating.'</h5></div>';
        echo '<div id = "btnMin"><input type="button" id ="minus" value ="-"/></div>';
        echo '<div id = "btnPl"><input type="button" id ="plus" value ="+"/></div> ';
        echo '<br/>';
        echo '</form>';
        echo '</div>';
        echo '</td>';
        $i++; 
        if ($i == 5) {
          echo '</tr><tr>';
        }
    }
     echo '</tr></table>';
}

    if(isset($_POST['minus'])){
        $newRating = 1;
        $ID = $_POST['progID'];

        $upsql = "UPDATE programmes SET Rating = Rating - $newRating WHERE progID='$ID'";
        $stmt = $mysqli->prepare($upsql);
        $stmt->execute();
    }

?>

Ive kept the ID field hidden as i dont want that to be displayed on the web page. I just want to update the rating of a particular ID.

any informatino will be appreciated


Solution

  • Change your query from:

    $upsql = "UPDATE programmes SET Rating = Rating - $newRating WHERE progID='$ID'";
    

    To this:

    $upsql = "UPDATE programmes SET Rating = Rating - $newRating WHERE ProgrammeID='$ID'";
    

    Hope it should work..