【问题标题】:PHP/MySQL: Deleting data from DBPHP/MySQL:从数据库中删除数据
【发布时间】:2018-01-08 23:03:42
【问题描述】:

这比标题可能让您相信的要复杂一些。我有一个功能可以在用户进入页面后立即查询我的数据库。然后查询返回idnote_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">&times;</button>
                        </form>
                  ';
                }
              }
              
            ?>
            
          </div>
        </div><!-- col -->

【问题讨论】:

  • 您的代码中有 SQL 注入,请阅读此内容以防止它发生。stackoverflow.com/questions/60174/…
  • “如果我提供了足够的信息来解决这个问题,请告诉我” - 实际上,没有。你漏掉了 DELETE 语句,那在哪里?
  • DELETE 语句尚未完整编写。在尝试浪费时间编写、删除和重写函数之前,我仍在研究如何让数据库知道要查找哪个 IDfunction delete_note() { include('includes/connection.php'); $username = $_SESSION['username']; }

标签: php mysql database sql-delete


【解决方案1】:

在您的删除表单中,您必须嵌入您在查询中选择的笔记的 ID

<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">&times;</button>
    //include a hidden field containing the records ID
    <input type="hidden" name="note_id" value="?" />
</form>

你会发现你的返回数组的结构是有限的。目前,您有 2 个数组,一个带有注释文本(我认为),一个带有注释 ID。我会将它组合成这样的一行(在 select_notes 中):

 $notes = [];
 while ($row = mysqli_fetch_assoc($result)){
   $notes[] = ['id' => $row['id'], 'note_name' => $row['note_name']];
 }
 return $notes;

这样你将拥有一个多维数组,就像数据库返回的一样,然后在你的 HTML 中:

foreach (select_notes() as $note) {
   echo '
<form action="notes.php" class="single-note-form" method="POST">
    <button name="edit_note" type="submit">'.$note['note_name'].'</button>
    <button class="text-danger" name="delete_note" type="submit">&times;</button>
  <input type="hidden" name="note_id" value="'.$note['id'].'" />
</form>';
}

或以其他方式将note_id 输入表单。

如果您需要一个 id 列表,使用 $ids = array_column($notes, 'id') 将其从多维数组中提取出来非常简单,因此使用组合结构不会丢失任何内容。事实上,它使代码更干净、更短、更简洁。

http://php.net/manual/en/function.array-column.php

但是无论如何,一旦它嵌入到表单中,它就会变得简单,因为它是通过 post 请求传递的。那么删除时只需$_POST['note_id']

您还应该在查询中使用准备好的语句,即使它是会话数据并且您认为它是干净的。谁知道接下来会发生什么变化,您可能会引入一种方法让用户修改该值,然后是开放季节。应始终进行 SQL 注入预防。只需很少的努力,您就会知道自己的代码是好的。

最后一件事:

$query  = "SELECT `id`, `note_name` FROM `notes` WHERE `username`='$username'";

我会说使用username 可能会在某些时候让您感到悲伤。这应该真正使用用户表中的id。现在您的用户名可能是唯一的,但从纯粹的性能角度来看,使用数字索引比字符串快得多。而且,它只是让我有些烦恼......

【讨论】:

  • You should also use prepared statements in your query 谢谢你,随着我在 PHP 方面的经验越来越丰富,我将更多地研究如何防止攻击。 You will find the structure of you return array to be to limiting, so you will have to modify this 那么您建议我如何创建它?如果我可以告诉我的脚本添加一个id 的索引,然后添加一个note_name 的索引并继续这样做,那么这已经解决了。有没有办法创建它?
  • 更新了!那应该很好,如果有任何语法错误,请见谅。或者,如果我发现任何变量不正常,有点匆忙,必须运行....
【解决方案2】:

我从您的问题中了解到,hte 用户登录并被发送到这个新页面,PHP 代码在该页面发回与其用户名关联的一个或多个注释。

您在页面上显示这些注释,但您想知道如何删除注释。

PHP 运行一次,然后停止。它离开页面上显示的注释。现在,您需要一种方法来 (1) 捕获用户交互(单击笔记)并 (2) 发送指令以从数据库中删除笔记。

一个很好的方法是使用 javascript/jQuery 来捕获用户单击事件,以及 (2) AJAX 向服务器上的另一个 PHP 文件发送/接收数据(不用担心,比它简单得多声音)。 PHP 文件将接收信息并运行 MySQL 指令以删除相应的注释。

这里有一些简单的 AJAX 示例,以便您了解它的工作原理。

https://stackoverflow.com/a/17974843/1447509

基本上,您的代码将如下所示:

$(document).on('click', '.user-note', function(){
  var tmp = $(this).attr('id'); //assuming the id contains the note_id and you can isolate that, perhaps with .split()
  $.ajax({
    type: 'post',
     url: 'name_of_php_file_on_your_server.php',
    data: 'note_id=' +tmp+ '&what2do=delete'
  }).done(function(d){
    alert(d); //displays whatever the above PHP file echo's back to javascript
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    • 1970-01-01
    • 2017-05-15
    相关资源
    最近更新 更多