【发布时间】:2018-01-08 23:03:42
【问题描述】:
这比标题可能让您相信的要复杂一些。我有一个功能可以在用户进入页面后立即查询我的数据库。然后查询返回id 和note_name(这些是我数据库中列中的名称)。我可以让笔记显示得很好,我遇到问题的地方是删除它们。我对如何动态告诉服务器当前正在选择哪个笔记感到非常困惑。
如果我提供了足够的信息来解决这个问题,请告诉我,我正在删除不必要的代码以节省空间。所有代码都在同一个.php 脚本中。
notes.php
select_notes() 函数
// 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>';
}
}
select_notes() 在 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 -->
【问题讨论】:
-
您的代码中有 SQL 注入,请阅读此内容以防止它发生。stackoverflow.com/questions/60174/…
-
“如果我提供了足够的信息来解决这个问题,请告诉我” - 实际上,没有。你漏掉了 DELETE 语句,那在哪里?
-
DELETE 语句尚未完整编写。在尝试浪费时间编写、删除和重写函数之前,我仍在研究如何让数据库知道要查找哪个
ID。function delete_note() { include('includes/connection.php'); $username = $_SESSION['username']; }
标签: php mysql database sql-delete