Home>

I am a new PHP user.
Pulling data from MYSQL as shown in the figure
The table is displayed.

Erase button in foreach minutes,
I wanted to delete only the ID in the same line, I tried variously,
When you press the delete button, all IDs disappear, or the data disappears line by line when loading a page.

I was trying to move php from a javascript function with onClick.
Was this idea wrong in the first place?
I would be pleased if someone could tell me the solution.

The code is as follows.
$pdo is a variable that is defined when displaying the table.


   
     
        ID 
        Name 
        Age 
        Affiliation 
        
     
  
  <? php foreach ($results as $result):?>
    
      
        <? php echo $result [id]?>
        <? php echo $result [name]?>
        <? php echo $result [age]?>
        <? php echo $result [department]?>
        
         <input onclick = "deletephp ()" type = "button" value = "delete" />
        
      
    
   <? php endforeach?>

  <script type = "text/javascript">
    function deletephp () {
      <? php
        $delete_id = $result [id];
        $delete = $pdo->prepare ("DELETE FROM test_php WHERE id = $delete_id");
        $delete->execute ();
      ?>
      }
   </script>

The table name is test_php,
php is version 5.4.16.

  • Answer # 1

    In the first place, PHP does not work in JavaScript.
    When the screen is displayed, PHP is running (check the html in the browser's "view source").

    If you want to delete only the data selected (clicked) from the list, it is common to pass the key such as id to PHP with Ajax and execute the deletion process in the background.

    If it is difficult, you can attach the same name to the button, add each id to value, and submit form.

    And in the current creation, $result is a value that has left foreach, so only the last data is kept
    The last data is deleted when the screen is displayed without pressing the delete button.
    Since it is a deletion process after the screen display process, it does not affect the display.
    It has been deleted on the database.