使用按钮更新数据库值

时间:2017-03-29 13:08:35

标签: javascript php sql

<?php 
include ('session.php'); 

$connection = mysqli_connect("localhost", "root", "" , "log_database"); 
$question_id = rand(1,2);
$query = "SELECT * FROM questions WHERE id='$question_id' "; 
$query_run = mysqli_query($connection,$query); 
$query_row = mysqli_num_rows($query_run); 

if ($query_row==1) { 
    foreach ($query_run as $row ) { 
        $option1 = $row['option1']; 
        $option2 = $row['option2']; 
        $money = $row['money'];
        $option1_clicked = $row['option1_clicked'];
        $option2_clicked = $row['option1_clicked'];
        $id_question = $row['id'];
    } 
} 

?>
<!DOCTYPE html>
<html>

<head>
    <title>Game</title>
    <link rel="stylesheet" type="text/css" href="game.css"> </head>

<body>

    <div id="content_div">
        <img id="title_img" src="wealthypinguin.png">
    </div>

    <div id="question_div">
        <span id="question">
            <?php echo $username; ?>, <br> for <span id="money">€ <?php echo $money; ?></span>,
        <br>would you rather...</span>
    </div>

    <div id="buttons_div">
        <button onclick="addOption1()" id="button1">
            <?php echo $option1; ?>
        </button>
        <br>
        <button onclick="addOption2()" id="button2">
            <?php echo $option2; ?>
        </button>
        <br>
        <button id="button3">
            Keep your money
        </button>
    </div>

</body>

    <script>
        function addOption1() {
            <?php 
                $option1_clicked = $option1_clicked + 1; 
                $queryOption1 = "UPDATE `questions` SET `option1_clicked` = '$option1_clicked' WHERE id='$question_id'";
                $query_run_option1 = mysqli_query($connection,$queryOption1);
            ?>
        }

        function addOption2() {
            <?php 
                $option2_clicked = $option2_clicked + 1; 
                $queryOption2 = "UPDATE `questions` SET `option2_clicked` = '$option2_clicked' WHERE id='$question_id'";
                $query_run_option2 = mysqli_query($connection,$queryOption2);  
            ?>
        }
    </script>

</html>

当我点击我的button1时,我想要实现的是,我的php变量$ option1_clicked被提升一个,新值在我的数据库中更新。 当我点击button2相同的结果时。

问题是,当我单击其中一个时,值会更新,但它会自动将两个值($ option1_clicked,$ option2_clicked)更新为相同的值。 因此,当option1_clicked从6变为7时,option2_clicked也获得值7.

1 个答案:

答案 0 :(得分:0)

Ajax是最好的方法。 看看: https://www.w3schools.com/xml/ajax_intro.asp

您可以在不离开当前网页的情况下向文件(通常是PHP文件)发送POST或GET查询。

它非常有用,对用户来说非常有用(你可以创建良好且流畅的用户界面),而且非常简单。