skip to Main Content

I’m trying to make a note change editor in php and MySQL. But I ran into a problem. There are a lot of notes and to get the right one, I decided to stuff the ID, date, text and title into the properties of the button, but I don’t know how to get the data of a specific note so that.

$sql = "SELECT * FROM notes WHERE id_user = ".$_SESSION['id_user']."";
if($result = mysqli_query($mySql, $sql)){
  $results='';
   foreach($result as $row) {
       $results.='<section class="notes-section section" id="notesCard">
                     <div id= "noteContent" class="note-content">
                         <div class="note-h2"><h2 id="headingH2">'.$row['heading'].'</h2></div>
                         <div class="note-text"><p id="textArea">'.$row['text_content'].'</p></div>
                         <div class="note-panel">
                             <label id="dateNotes" for="">'.$row['date'].'</label>
                             <form action="editNote.php" name="" method="post">
                                <button name="editNotes" id="edit" class="insert-btn btn" value="'.$row['id_notes'].'">Изменить</button>
                                <button name="deleteNotes" class="delete-btn btn" value="'.$row['id_notes'].'">Удалить</button>
                                </form>
                         </div>
                     </div>
                </section>';
     }
  echo $results;
} else {
  echo "Что-то пошло не так...";
}

if (isset($_POST['deleteNotes']) and is_numeric($_POST['deleteNotes'])) {
  $delete = $_POST['deleteNotes'];
  if ($mySql -> query("DELETE FROM `notes` WHERE `id_notes` = '$delete'")) {
    
    echo '<script>window.location = "./notes.php"</script>';
  }
}

2

Answers


  1. There are several ways you could approach this, one way that would make the page more user friendly would be to use AJAX / Fetch to issue the HTTP requests to your PHP script. This would save reloading the page if multiple items are to be edited.

    The following snippet will fail here because of limitations of SO but should give an idea how to send the request on your actual development site. The HTML is a mock up of what might be generated in the PHP code – note the omission of ALL id attributes and addition of the data-id to the section. This dataset attribute is the ID for this db record.

    const callback=(text)=>{
      alert(`do something interesting with ${text}`)
    };
    
    /*
      This looks at all forms on the page and assigns
      an event handler to look for `click` events that
      are attributed to the buttons within the form.
      
      Using `closest` to identify the parent `section`
      which has been modified to include `data-id` attribute
      (where data-id is the ID from db) rather than assigning
      to each button using `$row['id_notes']`
      
      A `FormData` object is used bring together the values
      you wish to send to the PHP script and the request is made
      using Fetch.
      
      The `callback` here is called when the request has been processed
      by the PHP script and the response sent.
    */
    document.querySelectorAll('form').forEach(f=>{
      f.addEventListener('click',e=>{
        e.preventDefault();
        
        if( e.target instanceof HTMLButtonElement ){
          let section=e.target.closest('section[data-id]')
          let id=section.dataset.id;
          let bttn=e.target.value;
    
          let fd=new FormData();
            fd.set('id',id);
            fd.set('bttn',bttn);
    
          console.clear();
          console.log( 'Send POST request to Server -> %s, %s', id, bttn )
    
          /* send Fetch (ajax) request */
          fetch( 'editNote.php',{ method:'POST', body:fd })
            .then(r=>r.text())
            .then(callback)
            .catch(alert)
        }
      });
    })
    <section class="notes-section section" data-id="NOTES_ID_1">
      <div id="noteContent" class="note-content">
        <div class="note-h2">
          <h2>This is Heading #1</h2>
        </div>
        <div class="note-text">
          <p>This is Paragraph #1</p>
        </div>
        <div class="note-panel">
          <span>This is date #1</span>
    
          <form action="editNote.php" method="post">
            <button name="action" class="insert-btn btn" value="edit">Изменить</button>
            <button name="action" class="delete-btn btn" value="delete">Удалить</button>
          </form>
        </div>
      </div>
    </section>
    
    <section class="notes-section section" data-id="NOTES_ID_2">
      <div id="noteContent" class="note-content">
        <div class="note-h2">
          <h2>This is Heading #2</h2>
        </div>
        <div class="note-text">
          <p>This is Paragraph #2</p>
        </div>
        <div class="note-panel">
          <span>This is date #2</span>
    
          <form action="editNote.php" method="post">
            <button name="action" class="insert-btn btn" value="edit">Изменить</button>
            <button name="action" class="delete-btn btn" value="delete">Удалить</button>
          </form>
        </div>
      </div>
    </section>
    
    <section class="notes-section section" data-id="NOTES_ID_3">
      <div id="noteContent" class="note-content">
        <div class="note-h2">
          <h2>This is Heading #3</h2>
        </div>
        <div class="note-text">
          <p>This is Paragraph #3</p>
        </div>
        <div class="note-panel">
          <span>This is date #3</span>
    
          <form action="editNote.php" method="post">
            <button name="action" class="insert-btn btn" value="edit">Изменить</button>
            <button name="action" class="delete-btn btn" value="delete">Удалить</button>
          </form>
        </div>
      </div>
    </section>

    The PHP to Process that request could be modified to use a prepared statement like this in simple form. This is untested.

    if(isset( 
        $_POST['bttn'],
        $_POST['id']
    )){
        if( $bttn=='delete' ){
            $sql='DELETE FROM `notes` WHERE `id_notes`=?';
            
            $stmt=$mySql->prepare( $sql );
            $stmt->bind_param('s',$id);
            $stmt->execute();
            
            # this is sent back to the `callback` function
            exit("Record #$id deleted.");
        }
    }
    
    Login or Signup to reply.
  2. If your form contains table with some records, you can name the inputs like this:

    $id=1;
    echo "<input name='f[$id][name]'>
    <input type=submit name='f[$id][edit]' value='Изменить'>
    <input type=submit name='f[$id][delete]' value='Удалить'>";
    
    $id=2;
    echo "<input name='f[$id][name]'>
    <input type=submit name='f[$id][edit]' value='Изменить'>
    <input type=submit name='f[$id][delete]' value='Удалить'>";
    

    In this case you will receive an array like that:

    $_REQUEST[f]=>[
      1=>[
        name=>'blabla',
        edit=>'Изменить'
      ],
      2=>[
        name=>'blabla2'
      ]
    ]
    

    The only field ‘edit’ or ‘delete’ will appear depending on button clicked.
    By the way tag ‘button’ does not submit form, it is only used in js with ‘onclick’ event.

    Another possibility is to name your buttons like this:

    $id=1;
    echo "<input name='f[$id][name]'>
    <input type=submit name='edit[$id]' value='Изменить'>
    <input type=submit name='delete[$id]' value='Удалить'>";
    
    $id=2;
    echo "<input name='f[$id][name]'>
    <input type=submit name='edit[$id]' value='Изменить'>
    <input type=submit name='delete[$id]' value='Удалить'>";
    

    Then the $_REQUEST array will contain only one element
    $_REQUEST[edit/delete][your_id]
    For example if it is ‘edit’ then the id you can get with key($_REQUEST[edit]) or array_keys($_REQUEST[edit])[0] or array_key_first($_REQUEST[edit]) (depends on php version)

    And one more possibility – you can wrap each record in separate FORM tags. In this case you will reduce post data and get only one record. you only need to put hidden input with record id.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search