Hey guise, I have a uni assignment; setting up backend code for a tour company website. Everything's gone swimmingly but I've run into issues implementing a system for rating the tour packages.
Implementation for the rating system: user clicks rate button, the rating score is added to a running total and the tally of ratings is incremented by one. The average rating is returned by using php to divide the running total by the tally of ratings. I don't have a table of individual rating scores, just three fields
TotalRatings = the cumulative total of ratings
RatingNo = the tally of ratings submitted, this increments by one when a new rating is submitted.
Tour_Rating = the result of TotalRatings divide by RatingNo.
the handle for my database is $dbh and the Tour_Id is submitted along with the rating value from the form.
My code is below.
if ($_POST[Tour_Rating] >= 1 && $_POST[Tour_Rating] <= 5)
{
try {
$rating =$dbh -> query( "SELECT TotalRatings FROM Tours WHERE Tour_Id = '$_POST[Tour_Id]'");
$count = $dbh-> query( "SELECT RatingNo FROM Tours WHERE Tour_Id = '$_POST[Tour_Id]'");
$postRating = intval( $_POST[Tour_Rating]);
$ratings = intval($rating);
$ratings += $postRating;
$counts = intval($count);
++$counts;
$avgRatings = $ratings/$counts;
$avgRating = intval($avgRatings);
} catch (exception $e){
echo "sql queries failed";
echo $e;
}
$sql = "UPDATE Tours SET TotalRatings = '$ratings', RatingNo = '$counts', Tour_Rating = '$avgRating' WHERE Tour_Id = '$_POST[Tour_Id]' ";
$dbh->exec($sql)
}
I've put intval($var) on all my variables because I kept getting "unable to convert to string" errors when executing the $sql line.
The variables aren't updating correctly in my database, the $counts field (RatingNo) isn't incrementing and the $ratings field (TotalRatings) appears to be displaying the input rating (from form, $postRating) plus 1.
Do I need to have the code block in the try catch as a function? or will it reexecute every time a new value is posted from the form?
If so can I use something like ->exec($function) to execute it?
Not sure whats wrong with it, any ideas?
(nb, sorry if these questions are basic, we've been taught very little php in this subject so I've been going off of online resources, hurray for regional universities.)