1

I am Working on the project with my school but I have no idea how to call a PHP function when HTML button is clicked

<?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>" ;
    } 
?>

it's the sqlUpdateTheScore(); function at the top

GodSSom
  • 11
  • 1
  • Please use parameter binding with prepared statements. This is not how you pass values to SQL. https://stackoverflow.com/questions/7537377/how-to-include-a-php-variable-inside-a-mysql-statement – Dharman Apr 04 '20 at 11:20

2 Answers2

0

You can't directly call php functions from html. (I also find this annoying)

There are two workarounds you can use. The easiest is a form:

<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
}

The other way is to use AJAX. Here is a good turorial.

mega12345mega
  • 503
  • 1
  • 6
  • 17
0

Try this

PHP:

Change your SAVE button part to

<button class="save_button" value=$i>SAVE</button>

Add

if (isset($_POST['idMinusOneString'])) {
    sqlUpdateTheScore($_POST['idMinusOneString']);
}


JS:

add AJAX (with jQuery)

$('.save_button').click(function() {
    $.ajax({
        type: "POST",
        url: "this.php",
        data: { idMinusOneString: $(this).val() }
    }).done(function( msg ) {
        alert( "Data Saved: " + msg );
    });
});
jef
  • 536
  • 1
  • 4
  • 14