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.
我是php新手,我需要帮助。查询每次在页面加载时运行,而不是单击按钮时。
<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.
这非常令人沮丧,因为我在循环中运行这个按钮,但每次按钮加载时,它都会自动运行mysql_query,而不是单击它时。
SOLVED! Check on AnthonyB's answer.
解决了!检查AnthonyB的答案。
3 个解决方案
#1
1
You should use an AJAX request, because there is no redirection nor reloading. To use the exemple below, you must include jQuery
您应该使用AJAX请求,因为没有重定向或重加载。要使用下面的示例,必须包含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
在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.
注意,mysql_*函数已被弃用。相反,使用sqmyli_ *函数或PDO。为了安全起见,您可以使用准备语句。
更多相关文章
- wordpress永久链接重新加载页面,而不是重定向到发布
- 在返回按钮上重新加载页面。
- 来自加载页面的Javascript响应未显示在中,尽管我可以在firebug中
- 如何加载json文件?
- 在simplexml_load_file中加载url时出错
- 单击保存按钮(PHP和MSQL)时如何保存记录列表
- 迭代文件夹中的CSV文件,并使用PHP将数据加载到MySQL中
- JSFiddle:无法从数据库加载Ajax数据
- PHP:如果用户没有按下提交按钮,则Mysql回滚多个查询(通过ajax完成)