dongxianghui3709 2016-11-29 07:01
浏览 42
已采纳

mysql_query会自动执行,但不会在onClick时执行

I'm a newbie in php and I need help with this. The query runs every time on page load and not when I click my button.

<input type="button" name="button" onclick="<?php 
                  $temp_id = $row_RecStudent['stu_id'];
                  mysql_query("UPDATE tbl_studentdetail SET stu_queue = 0 WHERE stu_id = $temp_id"); ?>" value="Unqueue" />

This is so frustrated because I run this button in a loop but every time the button loads it automatically run the mysql_query inside not when I click it.

SOLVED! Check on AnthonyB's answer.

  • 写回答

3条回答 默认 最新

  • duanlu1922 2016-11-29 07:35
    关注

    You should use an AJAX request, because there is no redirection nor reloading. To use the exemple below, you must include jQuery

    <!-- data-id is the id you got before -->    
    <input type="button" data-id="<?php echo $row_RecStudent['stu_id']; ?>" name="button" class="button-on-click" value="Unqueue" />
    
    <script type="text/javascript">
        $(function() {
            //On click on this kind of button
            $(".button-on-click").on('click', function() {
                var id = $(this).attr('data-id');
                //Send AJAX request on page youraction.php?id=X where X is data-id attribute's value
                //the ID used in mysql query
                $.ajax({
                    url: "youraction.php",
                    method: "GET",
                    data: {
                        id: id
                    }
                }).done(function() {
                    //Once it is done
                    console.log("OK!");
                });
            });
        });
    </script>
    

    On youraction.php

    <?php
    //Cast $_GET['id'] to integer to prevent SQL injection.
    //If there is no id given, stop
    if (empty($_GET['id'])) {
        exit();
    }
    $id = (int)$_GET['id'];
    mysql_query("UPDATE tbl_studentdetail SET stu_queue = 0 WHERE stu_id = $id");
    

    Be careful, mysql_* functions are deprecated. Instead, use mysqli_* functions or PDO. And you could prefere use prepared statement for security reason.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog