通过按钮将+1添加到MySQL值

时间:2016-01-12 21:43:45

标签: php mysql

我正在尝试启用一个计数器系统,它会在MySQL表中为特定值添加+1。但是,当用户按下+1时,它按可用行数乘以1,并将该值添加到原始值。例如,我在表中有5行,5 x 1是5.这将添加到现有总数中。

代码在这里:

<table class="table table-striped">
        <thead>
          <tr>
            <th>#</th>
            <th>Author</th>
            <th>Request</th>
            <th>Rating</th>
            <th>Options</th>
          </tr>
        </thead>
        <tbody>

<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT id, name, request, rating, report FROM requests WHERE visible     = 1 ORDER BY rating DESC";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_array($result)) {

if($_POST[rate]){ //they have clicked the submit button
                $error = ''; //truncate the errors
                if($error){ //errors have occurred
                    echo 'Sorry. The following error(s) occurred:<br>        <br>'.$error.'<br>&laquo; <a href="home.php">Back</a>';
                }else{ //no errors
                                    $id = $_POST['rate'];
                    mysql_query("UPDATE requests SET rating = rating + 1 WHERE id = $id");
                }
            }else{ //not clicked the submit button
                echo '

<form method="post" class="form-inline">

<tr><td>' . $row["id"]. '</td><td>' . $row["name"]. '</td><td>' . $row["request"]. '</td><td>

<button type="submit" class="btn btn-success" name="rate" value="' . $row["id"] . '">+ ' . $row["rating"] . '</button></td><td>

<button type="submit" class="btn btn-primary" name="" value="">Like (0)</button>
<button type="submit" class="btn btn-primary" name="" value="">Comment (0)    </button>
<button type="submit" class="btn btn-danger" name="" value="">Report</button></td></tr>
                </form>

';
            }


}
} else {
echo "There is currently no outstanding requests!";
}
$conn->close();
?>
        </tbody>
      </table>

1 个答案:

答案 0 :(得分:0)

定义之前的评分,然后+1;

示例

您需要在更新前添加此内容。编辑$ result ['rating'];无论代码如何回应目前的评级

$updatetrating = $result['rating'] +1;

然后在您的更新查询中将+1更改为$ currentrating,它应该通过添加1来更新该行。

示例

mysql_query("UPDATE `requests` SET `rating` = '$updaterating' WHERE `id` = '$id'");
            }