Monday, 3 September 2018

PHP associative array removes a value on the click

I'm a newbie and I'm learning PHP so any help would be greatly appreciated.

I've been struggling a whole day with this I have an array that represents user last actions and it just records day - time - "type of action" (and it's serialized and sent to mySQL DB.)
And I'm getting array like this:
---- EDITED ----
Array ( [0] => Array ( [Date] => 2011-02-06 [Time] => 06:48 PM [Entry] => Email sent 0 test ) [1] => Array ( [Date] => 2011-02-06 [Time] => 06:48 PM [Entry] => Email sent 1 test ) [2] => Array ( [Date] => 2011-02-06 [Time] => 06:48 PM [Entry] => Email sent 2 test ) )
And my question is, I want to add a small button/link in each row (when array is displayed) so that user can remove just that particular action
foreach ( $actionhistory as $row ) {
  foreach ( $row as $key => $value ) {
   echo "foo delete record - $value";
  }
  echo '';
}
Question: user now sees this in his browser:
2011-02-0606:48 PM Email sent 0 test
2011-02-0606:48 PM Email sent 1 test
2011-02-0606:48 PME mail sent 2 test
I want to add a link before each date. So when users clicks on that link - external page will be loaded and that particular "record" needs to be removed from the list.
E.G. User wants to remove entry
[2] => Array ( [Date] => 2011-02-06 [Time] => 06:48 PM [Entry] => Email sent 2 test )
he will click on the link beside that entry.... and that's where I have a problem. How do I remove that entry but keeping the rest ?

Why all these variables? And your array is wrongly built.
$actionhistory[] = array(
  "Date" => date("Y-m-d"),
  "Time" => date("h:i A"),
  "Entry" => "Email sent ".$row." test" //This is actually user action
);

What you want is sending through javascript a particular row of actions' history to a PHP script, which will delete this row from the database, and maybe also dynamically remove the row from your table. You need to add another element to your array, which is the unique ID in the database, except if you've got a unique key with date/time/action - which seems pretty stupid! Then using a JS library such as jQuery, use a simple interaction on a delete button in your row like this:
<?php
while ( $data = $query->fetch() ){
  echo '<tr><td....</td>
    <td><input type="button" value="delete" onclick="
      $.post(\'myScript.php?id='.$data['id'].'\',function(d){
        if ( d == 1 ){
          $(this).parents("tr").eq(0).remove();
        }
      });" /></td</tr>';
}
?>

Then myScript.php should take care of $_POST['id'], delete the corresponding row, and echo 1 if it was successful, so the row is removed. [Edited, $_POST, not $_GET!]

0 comments:

Post a Comment