Kenny Kenny - 9 months ago 58
MySQL Question

mysql_query executes automatically but not when 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.

So I modified my code by using the form isset method but it still loads. Is it the same problem like you guys mentioned where php codes run first before html and javascript?

<form action="list_student.php" method="POST">
<input type="button" name="queue" value='Add to Queue' />

$temp_id = $row_RecStudent['stu_id'];
mysql_query("UPDATE tbl_studentdetail SET stu_queue = 0 WHERE stu_id = $temp_id");
} ?>

Answer Source

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
                url: "youraction.php",
                method: "GET",
                data: {
                    id: id
            }).done(function() {
                //Once it is done

On youraction.php

//Cast $_GET['id'] to integer to prevent SQL injection.
//If there is no id given, stop
if (empty($_GET['id'])) {
$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.