drutjkpsr67393592 2009-08-12 06:51
浏览 211
已采纳

使用Ajax请求从数据库中删除记录

I am using php / mysql and protype.js to delete record from a table. The problem is that the record in the database is not deleted.

index.php:

       <a href="javascript: deleteId('<?php echo $studentVo->id?>')">Delete</a></td>

Script is

   function deleteId(id)
   {
       alert("ID : "+id);
       new Ajax.Request('delete.php?action=Delete&id='+id,{method:'post'});
       $(id).remove(); // because <tr id='".$row[id]."'> :)

   }

delete.php

     <?php
      /* Database connection */
      include('configuration.php');
      echo "hello,...";
      if(isset($_POST['id'])){
          $ID = $_POST['id'];
          $sql = 'DELETE FROM student where id="'.$ID.'"';
          mysql_query($sql);
      } 
      else { echo '0'; }
     ?>

alert("ID : "+id); is working properly but the code after that is not.

  • 写回答

3条回答 默认 最新

  • dongzan9069 2009-08-12 06:58
    关注

    You are using a GET request, from JS :

    {method:'get'}
    

    And your PHP code uses data he thinks arrives as POST :

    $ID = $_POST['id'];
    

    You should use the same method on both sides.

    (As you are modifying / deleting data, you should probably use POST)


    As a sidenote, you should definitly escape/protected/check the data you are using in the SQL query, to avoid SQL injections, using, for instance, intval as you are working with an integer ; you'd use mysql_real_escape_string if you were working with a string.

    Another way would be to stop using the old mysql extension, and start using mysli or PDO, which means you could use prepared statements (mysqli, pdo)


    EDIT after the comment : you also, now that the request is made in POST, need to change the way parameters are passed : they should not be passed in the URL anymore.

    I suppose that something like this should work :

    var myAjax = new Ajax.Request(
      'delete.php',
      {
        method: 'post',
        parameters: {action: id}
      });
    

    Or you could also use something like this, building the parameters string yourself :

    var myAjax = new Ajax.Request(
      'delete.php',
      {
        method: 'post',
        parameters: 'action=' + id
      });
    

    (Not tested, so you might have to change a few things ;-) )

    For more informations, take a look at Ajax.Request and Ajax options :-)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 怎么实现只排序每行中的第二列的数 如果比两数都大就放在第三列中 比两数都小就放在第一列中(语言-c语言)
  • ¥15 应用商店如何检测在架应用内容是否违规?
  • ¥15 Ubuntu系统配置PX4
  • ¥20 MATLAB间接平差计算
  • ¥50 nw.js调用activex
  • ¥15 数据库获取信息反馈出错,直接查询了ref字段并且还使用了User文档的_id而不是自己的
  • ¥15 将安全信息用到以下对象时发生以下错误:c:dumpstack.log.tmp 另一个程序正在使用此文件,因此无法访问
  • ¥15 速度位置规划实现精确定位的问题
  • ¥15 MAC虚拟机(win11)USB插上后无串口com,无法烧录
  • ¥15 代码问题:df = pd.read_excel('c:\User\18343\Desktop\wpsdata.xlxs')路径读不到