无法执行语句(42S22 - 1054 - "字段列表"中的未知列) zf2



我是 ZF2 的新手,我正在尝试将数据删除到数据库,但数据无法删除,错误语句无法执行(42S22 - 1054 - "字段列表"中的未知列"(

我的观点

<?php foreach ($this->list as $data): ?>
<tr>
<td>
<?php echo $data->id ?>
</td>
<a href="<?php echo $this->url('mif',array('action'=>'delete', 'id' => $data->id));?>">Delete</a>  

我的控制器

public function deleteAction()  
{  
$request = $this->getRequest();
$post = (int) $this->params()->fromRoute('id', null);
$storage = MiffModelStorage::factory($this->getDb(), $this->getConfig());
$user = new MiffModel($storage);
$del = $user->del($post);
if($del){
$success = true;
$msg = 'Data sudah dihapus.';
}else{
$success = false;
$msg = 'gagal.';
}     
$view = new ViewModel();
$view->setTemplate('mif/index');

我的模型

public function del($post){
$delete = "DELETE from test where id = $post";
$db = $this->_db;
$result = $this->_db->query($delete, $db::QUERY_MODE_EXECUTE);
return $result;
}
}

由于接受的答案是安全漏洞,我提出这个建议:

此解决方案基于使用 PDO。

public function del($post){
$stmt = $this->_db->prepare('DELETE from test where id = :id');
// Check if there is a post exists, if not throw exception
if(empty($post)) {
throw new Exception('wrong or empty data provided');
}
$stmt->bindParam(':id', $post);
return $stmt->execute();
}
  • 从此链接

  • 引用
  • 预准备语句的参数不需要引用; 驱动程序会自动处理此问题。如果仅应用,则 使用预准备语句,开发者可以确定没有SQL 将发生注入(但是,如果查询的其他部分 使用未转义的输入构建,SQL注入仍然是可能的(。

看起来有人在评论中发布了答案,但似乎并不那么清楚,他们没有正确转义字符串以使用 $post 值。

这是我建议做的:

经过编辑以使用最佳实践

public function del($post)
{
$stmt = $this->_db->prepare('DELETE from test where id = :id');
// Check if there is a post exists, if not throw exception
if(empty($post)) {
throw new Exception('wrong or empty data provided');
}
$stmt->bindParam(':id', $post);
return $stmt->execute();
}

最新更新