首页 > 解决方案 > 单击 PHP 回显 HTML 按钮时运行 PHP 函数

问题描述

我正在和我的学校一起做这个项目,但我不知道如何在单击 HTML 按钮时调用 PHP 函数

<?php
function sqlUpdateTheScore($idMinusOneString){
    $idminusOneVal=(int)$idMinusOneVal;
    $MsgQuery=mysqli_query($conn,"UPDATE Point SET Point=".returnCurrentPoint($idMinusOneVal)."WHERE id=".($idMinusOneVal+1).";");
}
 for($i=0;$i<$tot;$i++){
        print "<tr>" ; 
        print "<td align='center'>" .$tot_result[$i][0]."</td>";
        print "<td align='center'>" .$tot_result[$i][1]."</td>";
        print "<td align='center'>" .$tot_result[$i][2]."</td>";
        print "<td align='center'><button id='dec_".$i."' onclick='decreaseByOne(".$i.");'>-1</button><div id='pointOfStudent".$i."'>" .$tot_result[$i][3]."</div><button id='inc_".$i."' onclick='increaseByOne($i);'>+1</button></td>";
        print "<td align='center'><button onclick='sqlUpdateTheScore($i);'>SAVE</button></td>";
        print "</tr>" ;
    } 
?>

这是sqlUpdateTheScore(); 顶部的功能

标签: phphtmlmysql

解决方案


您不能直接从 html 调用 php 函数。(我也觉得这很烦人)

您可以使用两种解决方法。最简单的是一个表格:

<form action="thePage.php" method="POST">
    <input type="text" name="newValue" id="newValue" hidden />
    <button onclick="changeValue()">Change Value</button>
    <input type="submit" value="SAVE" name="submit" />
</form>

JavaScript:

function changeValue() {
    document.getElementById("newValue").innerText = "Some new value";
}

PHP:

if (isset($_POST["submit"])) {
    $newValue = $_POST["newValue"]; // You can then run functions off this value
}

另一种方法是使用 AJAX。是一个很好的教程。


推荐阅读