javascript - 使用 JQuery 删除数据库行

标签 javascript php jquery mysql ajax

我正在使用 PHP 函数将任何 2D PHP 数组格式化为 HTML 表,在该表中我需要在每一行中添加一个删除按钮,因此当用户单击删除按钮时,jQuery 应该采用特定字段(3 个字段)并提交一个 php 文件,它应该在不重新加载页面的情况下给出响应,我在同一个 PHP 文件中有几个动态表,所以我使用 $table_name 作为表单 ID 来区分 FORMS,并且在 del.php (在哪里我的表单已提交)我决定我应该查找哪个表以使用 PRIMARY KEY 删除行。我的问题是我是否必须在每个表中创建表单才能完成此任务?或者我可以简单地放置一些字段并使用 jQuery 提交表单吗?

任何帮助将不胜感激。

function formatArrayToTable($foo, $deletable = 0, $restaurant_id ='', $table_name = '') {
  //open table
  echo '<table class="imagetable">';

  // our control variable
  $first = true;

  foreach($foo as $key1 => $val1) {
    //if first time through, we need a header row
    if($first){
      echo '<tr>';
      foreach($val1 as $key2 => $value2) {
        echo '<th>'.$key2.'</th>';
      }

      if($deletable) {
        echo "<th>'Delete'</th>";
      }

      echo '</tr>';

      //set control to false
      $first = false;
    }

    echo '<tr>';

    foreach($val1 as $key2 => $value2) {
      echo '<td>'.$value2.'</td>';
    }

    if($deletable) {
      $primary = $val1["id"];

      echo "<input type='hidden' name='table_name' value='{$table_name}' />";
      echo "<input type='hidden' name='restaurant_id' value='{$restaurant_id}' />";
      echo "<td><input class='delete_class' type=\"button\" name=\"delete_id\" value={$primary} onclick='SubmitForm($table_name)'/></td>" ;
    }
    echo '</tr>';
  }
  echo '</table>';
}

我的 Javascript 函数

function SubmitForm(formId){
  var message = "";
  $("#"+formId+" input").each(function() {
    message += $(this).attr("name");
  });

  $.ajax({
    type: "POST",
    url: "del.php",
    data: message,
    success: 
      function() {
        $('#message').html("<h2>Contact Form Submitted!</h2>")
          .append("<p>Entry is Deleted </p>")
          .hide()
      }
  });
}

-问候

最佳答案

您的问题似乎是问您是否可以仅使用 jQuery 从数据库中删除项目。通常,据我所知,这是不可行的,因为您的数据库是服务器端的,而您的 jQuery 是客户端的。话虽这么说,我敢肯定有些怪人已经为它创建了一个库。尽管如此,要回答您的实际问题:

您需要了解如何使用 jQuery 模拟直接从数据库表中删除表行。这是您所需的 jQuery 的粗略示例、当前 php 函数的示例输出以及应该存在于 del.php 中以处理实际删除的内容。

示例表

快速笔记。添加 thead 和 tbody 标签以帮助浏览器显示。删除 onclick="" 位,您使用的是 jQuery,因此只需添加带有 JavaScript block 的回调。确保您的代码将“.submittable”类(或其他描述性名称)添加到您的表中。您可以将整个表包装在一个表单中,然后使用像 jquery form 这样的插件处理每个表单的提交,但这对于少数几个领域来说似乎有点矫枉过正,所以我将解释如何处理原 Material 。

<table class="imagetable submittable">
  <thead>
    <tr>
      <th>id</th>
      <th>name</th>
      <th>file</th>
      <th>meta</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        <input type='hidden' name='table_name' value='secret_image_table' />
        <input type='hidden' name='restaurant_id' value='123' />
        <input class='delete_class' type='button' name='delete_id' value="Delete" />
      </td>
      <td>Silly Cat Image</td>
      <td>yarny-cat.jpg</td>
      <td>{"submitter":"De Zéro Toxin"}</td>
    </tr>
  </tbody>
</table>

jQuery 代码块

从任何客户端表单、ajax 或其他方式提交表名都是一个糟糕的主意。这是非常敏感的信息,任何程序员/黑客在尝试攻击您的网站时都可以利用这些信息为自己谋取利益。尽管如此,我不知道它的用法,所以在你的设置中可能没问题。不过仍然是不好的做法。

// any time any element with the 'delete_class' on it is clicked, then
$(document).on('click', '.delete_class', function(e) {
  var row = $(this).closest('tr');

  var data = {
    table: $('[name="table_name"]').val(),
    id: $('[name="restaurant_id"]').val()
  };

  $.post('del.php', data, function(r) {
    // do some special stuff with your json response 'r' (javascript object)
    ...

    // do what you showed us you are doing, displaying a message
    $('#message').html("<h2>Contact Form Submitted!</h2>")
      .append("<p>Entry is Deleted </p>")
      .hide();

    // remove the row, since it is gone from the DB
    row.remove();
  }, 'json');
});

del.php

同样,提交时的表名 = 坏主意。被打马。

// define a delete function that accepts a table name an id

// define some functions to sanitize your $_POST data, to prevent SQL Injection.
// run said functions before you get to this point

// json response function, since you said you want a response from your js
function respond($data) {
  echo @json_encode($data);
  exit;
}

if (empty($_POST)) respond(array('error' => 'Invalid request')); 

$table_name = $_POST['table_name'];
$id = $_POST['id'];

$response = deleteRecord($table_name, $id);

if ($response == $what_you_expect_on_a_successful_delete) {
  // create a response message, in associative array form
  $message = array('success' => true);

  // add some other information to your message as needed
  $message['sideNote'] = 'I like waffles.';

  // respond with your message
  respond($message);
}

// if we got this far your delete failed
respond(array('error' => 'Request Failed'));

希望这对您有所帮助。

关于javascript - 使用 JQuery 删除数据库行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20754465/

相关文章:

javascript - 尝试从js中的另一个文件调用变量时出错

php - 如何为新 bundle 编写Symfony Flex配方?

javascript - 如何从 PHP 将 JSON 传回我的 AJAX 请求?

javascript - Vue.js - 如何从另一个组件调用方法

javascript - 我是在正确地链接 Promise 还是犯了罪?

javascript - react +Javascript :-Component will update is getting called too many times causing my application to crash

php - URL Mod 重写

javascript - Plupload、IE8 和 HTML4 运行时不触发添加文件对话框

javascript - jquery中通过循环获取值

javascript - 使用 jquery 定位父对象