php - 我想删除 php mysql 中的 where id=$POST ['id' ]

标签 php mysql wordpress

我的删除条目代码是这样的,但它没有做任何事情

HTML

<form id="form3" name="form3" method="post" onsubmit="return validateForm();" action="">
    Id <input type="text" class="txt" name="id" /><br />
    <input type="submit" id="delete" value="delete"/>
</form>

PHP

global $wpdb;

if ( isset ( $_POST['id'] ) && ! empty ( $_POST['id']  ))
{
    $wpdb->query("DELETE " . PRO_TABLE_PREFIX . "tutorial  WHERE id='{$_POST['id']}'");
}

最佳答案

为了避免这样的混淆,我总是在需要连接字符串的地方使用sprintf()

更改:

global $wpdb;
if ( isset ( $_POST['id'] ) && ! empty ( $_POST['id']  )) {
    $wpdb->query("DELETE " . PRO_TABLE_PREFIX . "tutorial  WHERE id='{$_POST['id']}'");
}

至:

global $wpdb;

if ( isset ( $_POST['id'] ) )) {    

   $wpdb->query(sprintf("DELETE %stutorial  WHERE id='%s'", PRO_TABLE_PREFIX, $_POST['id']));
}

需要注意的几点:

1) 您容易受到 SQL 注入(inject)
2) 使用 isset() 确定 $_POST['id'] 的键是否实际上不是 NULL 后,您不需要通过 empty()

检查它是否为空

更新

您应该真正测试 $_POST['id'] 是否有效。我建议您实现一个函数,例如 is_id_valid()

function is_id_valid(&$id){ //<-- IMPORTANT, Argument should be a reference 

  if ( ! isset($id) ){
     return false;
  }

  if ( empty($id) ){
    return false;
  }

  // add this if you expect $id to be a numeric value
  // otherwise just ignore - do not add
  if ( ! is_numeric($id) ){
    return false;  
  }

  //it's also a good to validate the length 
  if ( strlen($id) > ... && strlen($id) < ... ){
     return false;
  } 

  //seems like all tests passed
  return true;
}

然后你会使用它,比如

if ( is_id_valid($_POST['id']) !== false ){
   ....
}

警告:它仍然容易受到 SQL 注入(inject)攻击

关于php - 我想删除 php mysql 中的 where id=$POST ['id' ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14108583/

相关文章:

php - 导入巨大的 csv 并加载数据本地文件,其中一些字段用“括起来”

mysql - 加入两个mysql表并按日期显示数据

javascript - 页面重叠在页脚 div 上

php - 在 mysql 中向我写一个困难的查询?

php - html文件夹外的文件和图像

php - 自动完成搜索查询mysql

mysql - 将列插入表中,使用现有列值作为现有行的默认值

css - 背景 :cover cutting off image

wordpress - 本地主机 WordPress 不工作

php - 在 json 代码igniter 中从 Controller 检索数据