根据单选按钮值更新数据库

时间:2015-10-29 17:17:51

标签: php mysql mysqli

我正在尝试为网站创建评级系统。我能够从数据库中检索项目并在每个项目下显示5个单选按钮。 5个单选按钮的值为1到5.

我试图根据所选单选按钮的值更新每个项目的评级。

我有以下代码:

<?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"><h4>'.$obj->Rating.'</h4></div>';
        echo '<input type="radio" class="rating-input" id="rate" name="rate" value="1">';
        echo '<input type="radio" class="rating-input" id="rate" name="rate" value="2">';
        echo '<input type="radio" class="rating-input" id="rate" name="rate" value="3">';
        echo '<input type="radio" class="rating-input" id="rate" name="rate" value="4">';
        echo '<input type="radio" class="rating-input" id="rate" name="rate" value="5">';
        echo '<br/>';
        echo '</form>';
        echo '</div>';
        echo '</td>';
        $i++; 
        if ($i == 5 OR $i == 10) {
          echo '</tr><tr>';
        }
    }
     echo '</tr></table>';
}



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

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

?>

除了Update语句之外,所有代码都正常工作,其中im添加到已存储在数据库中的当前评级。

有人可以帮我解决这个问题吗

谢谢!

1 个答案:

答案 0 :(得分:1)

您需要捕获错误条件,这将告诉您语句的错误(如果有的话)。此外,您应该正确使用预准备语句以避免安全问题。最后,您应该在显示数据之前插入数据库,以确保您显示最新数据。

if(isset($_POST['rate'])){
    $upsql = "UPDATE programmes SET Rating = Rating + ? WHERE ProgrammeID = ?";
    $stmt = $mysqli->prepare($upsql);
    if (!$stmt) {
        echo "Error preparing: " . $mysqli->error . "<br/>";
    } else {
        $stmt->bind_param('is', $_POST['rate'], $_POST['progID']);
        if (!$stmt->execute()) {
            echo "Error executing: " . $mysqli->error . "<br/>";
        } else {
            echo $stmt->affected_rows . "rows affected<br/>";
        }
    }
}

$results = $mysqli->query("SELECT * FROM programmes ORDER BY ProgrammeName ASC");
if ($results) { 
...