如何通过按钮单击随机int更新mysqli查询?

时间:2016-03-15 17:00:22

标签: php mysql

我正在尝试使用PHP创建一个程序,允许用户喜欢(酷)或不喜欢(不冷静)来自我的数据库的随机图像。当用户点击冷却按钮时,带有“酷”列的表格“图像”将以+1更新。随机图像由'selectedRandomImage'函数创建。

我遇到的问题是当我按下“酷”按钮并触发冷却功能时,页面重新加载并随机变量得到改变。因此,更新查询不会更新当前图像,但会更新按下“酷”按钮后显示的图像。

name =“cool”的提交按钮位于不同的php页面上。

有关如何解决此问题的任何想法? 随意提供我的代码的任何反馈,因为我是新的,我想改进。 : - )

    <form action="" method="post" class="text-center">

        <input style="margin-right: 0 !important;" class="btn btn-success" type="submit" name="cool" value="Cool">
        <input class="btn btn-danger" type="submit" name="nietcool" value="Niet Cool">
    </form>


    class Cool{
    var $randomSoms;

    function checkHowManyImages(){
        $con = connectDB();
        $aantalImage = $con->query("SELECT COUNT(image) FROM image");
        $row = $aantalImage->fetch_row();
        return $row[0];
    }
    function selectRandom(){
        $random = rand(1, $this->checkHowManyImages());
        return $random;
    }

    function selectRandomImage(){
        $con = connectDB();
        $random = $this->randomSoms = $this->selectRandom(); // maakt nieuwe random aan

        echo "de random id in de selectRandomImage function is: " . $this->randomSoms; // check if random is the same

        $result = $con->query("SELECT image, name FROM image WHERE id = '$random'");

        while  ($row = mysqli_fetch_array($result)): ?>
            <div class="text-center"><img src="<?php echo $row["image"] ?>" alt="<?php echo $row["name"] ?>" class="img-thumbnail "></div>
        <?php endwhile;

    }
    function cool(){
        $randomId = $this->randomSoms;
        $con = connectDB();
        $con->query("UPDATE image SET cool = cool + 1 WHERE id = '$randomId'");
    }

}
$randomimage = new Cool;
$randomimage ->selectRandomImage();
echo "de random id in buiten de selectRandomImage function is: ".$randomimage->randomSoms; // random id

// Probleem is dat er plus 1 wordt gedaan bij de volgende random omdat de pagina na button click gerefreshed wordt.:-(
if(isset($_POST['cool'])) {
    $randomimage->cool();

}

1 个答案:

答案 0 :(得分:0)

为什么不在表单中使用隐藏的输入来发送当前图片ID?

<form action="" method="post" class="text-center">
<input type="hidden" name="randomid" value="<?php echo $randomid;?>">
    <input style="margin-right: 0 !important;" class="btn btn-success" type="submit" name="cool" value="Cool">
    <input class="btn btn-danger" type="submit" name="nietcool" value="Niet Cool">

</form>

。 。 。

    function cool(){
    $randomId = $_POST['randomid'];
    $con = connectDB();
    $con->query("UPDATE image SET cool = cool + 1 WHERE id = '$randomId'");
}