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 求高通平台Softsim调试经验
  • ¥15 canal如何实现将mysql多张表(月表)采集入库到目标表中(一张表)?
  • ¥15 wpf ScrollViewer实现冻结左侧宽度w范围内的视图
  • ¥15 栅极驱动低侧烧毁MOSFET
  • ¥30 写segy数据时出错3
  • ¥100 linux下qt运行QCefView demo报错
  • ¥50 F1C100S下的红外解码IR_RX驱动问题
  • ¥20 基于matlab的航迹融合 航迹关联 航迹插补
  • ¥15 用Matlab实现图中的光线追迹
  • ¥15 联想笔记本开机出现系统更新界面