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
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 thesection
. Thisdataset
attribute is the ID for this db record.The PHP to Process that request could be modified to use a
prepared statement
like this in simple form. This is untested.If your form contains table with some records, you can name the inputs like this:
In this case you will receive an array like that:
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:
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.