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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料