mysqli_query是否在函数内部自动激活



无论出于何种原因,我的数据库都会像函数运行一样进行更新,但它从未响应任何内容。当我重新加载页面时,它会自动将名称设置为"John",但我从未单击该按钮。

<?php
function a(){
$con = mysqli_connect("localhost", "example", "example", "example");
$sql = "UPDATE User SET name = 'John' WHERE name = '$username'";
mysqli_query($con, $sql);
//test to see if function fires:
echo "function executed";
}
?>

这是我的html/javascript代码:

<script type="text/javascript">
function b(){
document.write("<?php a(); ?>");
//test if javascript function executes:
alert("function b() executed");
}
</script>
<button onclick="b()">Click me!</button>

我不得不使用javascript,因为我的整个页面都是一个表单(用于单个保存按钮(,并且不能直接让按钮执行php函数。

我只是很困惑为什么它没有回声,但当我重新加载页面时,它确实更新了我的数据库,请帮助。

当然,由于这行,每次加载页面时都会更新数据库

document.write("<?php a(); ?>");

每次加载页面时,都会调用a()来更新数据库

函数a不回显"function executed"的原因是它确实,但您在页面上看不到它,因为它在它的行中回显。我相信你会在页面源中看到它。

当PHP解析器解析您的脚本时,它将生成并响应以下

document.write("function executed");

您需要使用Ajax通过单击button来调用PHP脚本。以下内容会起作用。

不要在页面上包含PHP脚本,只有在单击button后才会调用mysql。

<script type="text/javascript">
function ajax(url) {
var http = false;
if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...
http = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 6 and older
http = new ActiveXObject("Microsoft.XMLHTTP");
}
if (! http) {
// old browser or terminal maybe?
return false;
}
http.onreadystatechange = function() {
if ((http.readyState == 4) && (http.status == 200)) {
// do stuff with the html/json/data returned
// this alert will trigger once the PHP is run.
alert(http.responseText);
}
}
http.open('GET',url,true);
http.send(null);
}
function b(){
// call the code on PHP script to run.
ajax("/path/to/your/php");
//test if javascript function executes:
// this alert should fire first.
alert("function b() executed");
}
</script>
<button onclick="b()">Click me!</button>

最新更新