Peter Pik Peter Pik - 6 months ago 23
SQL Question

<button> execute mysql query on click

I am new to PHP and I am trying to execute a remove query when the remove button is clicked. At the moment the current if statement is not triggered, so how can I trigger the if statement from a button and how can I get the id of the button that was tapped?

<?

while($row = mysqli_fetch_array($result)) {
echo "<td>" . $row["id"] . "</td>";
echo "<td>" . $row["teamName"] . "</td>";
echo "<td>" . $row["name"] . "</td>";
echo "<td>" . $row["country"] . "</td>";
echo "<td>" . $row["birthday"] . "</td>";
echo "<td><button type='button' class='btn btn-default ' aria-label='Left Align'>Edit</button> ";
echo "<button type='button' class='btn btn btn-danger' aria-label='Left Align' name='remove' value='remove'>Remove</button></td>";


}
?>

if(isset($_POST['remove'])){
$removeQuery = "UPDATE Players Where id='ID PRESSED?'";
header('Location: '.$_SERVER['REQUEST_URI']);
}

Answer

you can simply change the button to link and get the id using $_GET

 <?php

 while($row = mysqli_fetch_array($result)) { 
     echo   "<td>" . $row["id"] . "</td>";  
     echo   "<td>" . $row["teamName"] . "</td>";   
     echo   "<td>" . $row["name"] . "</td>";
     echo   "<td>" . $row["country"] . "</td>";
     echo   "<td>" . $row["birthday"] . "</td>";
     echo   "<td><button type='button' class='btn btn-default ' aria-label='Left Align'>Edit</button>   ";
     // change yourpage.php to the page that executes the query
     echo  "<a href='yourpage.php?del=".$row['id']."' class='btn btn btn-danger' aria-label='Left Align' name='remove' value='remove'>Remove</button></td>";    
 }


 if(isset($_GET['del'])){
     $id = (int)$_GET['del'];
     $removeQuery = "UPDATE Players Where id = $id";
     header('Location: '.$_SERVER['REQUEST_URI']);
 }