This is a little more complicated than the title may lead you to believe. I have a function that queries my DB as soon as a user enters the page. The query then returns the id
and note_name
(these are the names in the columns in my DB). I can get the notes to display just fine, where I'm having trouble is deleting them. I am very confused on how to dynamically tell the server which note is currently being selected.
Let me know if I have supplied enough information to solve this problem, I am removing unnecessary code to save space. All code is in the same .php
script.
notes.php
select_notes() function
// query DB for pre-existing notes
function select_notes() {
include('includes/connection.php');
$username = $_SESSION['username'];
// make READ query to the db and return the results
$query = "SELECT `id`, `note_name` FROM `notes` WHERE `username`='$username'";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
// create empty array for future use
$note_id = [];
$note_name = [];
while ($row = mysqli_fetch_assoc($result)) {
// push all the data from $row into $note_name array
array_push($note_id, $row['id']);
array_push($note_name, $row['note_name']);
}
// close connection and return array containing note details from DB
mysqli_close($conn);
return [ $note_id, $note_name ];
} else {
mysqli_close($conn);
echo '<p>No notes available</p>';
}
}
Where select_notes()
is being called in the HTML
<div class="saved-notes col-10 offset-1 col-md-4 offset-md-0">
<header class="text-center">
<h2>Saved Notes</h2>
</header>
<div class="pt-2">
<form action="<?php htmlspecialchars($_SERVER['PHP_SELF']); ?>" class="form-inline px-1" method="POST">
<input class="form-control mb-1 mr-1" name="note_name" type="text">
<input class="btn btn-success btn-sm" name="create_note" type="submit" value="Save">
</form>
<?php
if ($_POST['create_note']) {
insert_note();
}
list($note_id, $note_name) = select_notes();
foreach (select_notes() as $note) {
foreach ($note as $value) {
echo '
<form action="notes.php" class="single-note-form" method="POST">
<button name="edit_note" type="submit">'.$value.'</button>
<button class="text-danger" name="delete_note" type="submit">×</button>
</form>
';
}
}
?>
</div>
</div><!-- col -->