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 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同