2015-04-02 59 views
0

我想在我的MVC网站中实现一个删除功能。我有以下错误PHP MVC SQL语法错误

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'id=27' at line 1 

此刻当我试图解决我的ID 27已经硬编码的错误,我已经通过语法寻找一个简单的行删除无处不在(如http://www.w3schools.com/php/php_mysql_delete.asp),但似乎无法找到为什么我得到错误?

deleteItem功能

 function deleteItem($parameters) { 
     $id = '27'; 

     if ($this->model->deleteItem($id)) { 
      $this->model->hasDeleteFailed = false; 
      $this->model->setDeleteItemConfirmation(); 
      return (true); 
     } 
     else 
      $this->model->deleteItemError (DELETE_ITEM_ERROR_STR); 
    } 

SQL代码

public function deleteItem($id) { 
    $delId = $id; 
    $sqlQuery = "DELETE FROM items"; 
    $sqlQuery .= "WHERE id=$delId;"; 

    $result = $this->getDbManager() -> executeQuery ($sqlQuery); 
} 
+0

您能指定位置吗? – Hayes121 2015-04-02 12:09:10

回答

1

此:

$sqlQuery = "DELETE FROM items"; 
$sqlQuery .= "WHERE id=$delId;"; 

应该是:

$sqlQuery = "DELETE FROM items "; // note the extra space at the end 
$sqlQuery .= "WHERE id=$delId;"; 

或者:在$ sqlquery的

$sqlQuery = "DELETE FROM items"; 
$sqlQuery .= " WHERE id=$delId;"; // note the extra space at the beggining 
+0

非常感谢!这个错误让我的头发一直在撕裂!总是小事! – Hayes121 2015-04-02 12:10:24

+1

没问题。如果它符合您的要求,请随时接受答案。在出现语法错误的情况下,请遵守**总是**'var_dump'您的SQL语句的习惯。 – D4V1D 2015-04-02 12:10:47

1
public function deleteItem($id) { 
    $delId = $id; 
    $sqlQuery = "DELETE FROM items"; 
    $sqlQuery .= " WHERE id=$delId;"; 

    $result = $this->getDbManager() -> executeQuery ($sqlQuery); 
} 

使用空间,我提了。

2

代码

$sqlQuery = "DELETE FROM items"; 
$sqlQuery .= "WHERE id=$delId;"; 

是问题,因为你的SQL语句几乎达:

DELETE FROM itemsWHERE id=$delId 

注意到有词“项”和字之间没有空格“WHERE “在SQL语句中。

另外,你不妨重构代码以

$sqlQuery = "DELETE FROM items WHERE id=$delId"; 

,因为有超过两个字符串创建的SQL语句没有任何好处。

此外,您需要正确地逃避您的SQL输入参数,以防止SQL Injection attacks。我不知道你正在使用哪个PHP框架,所以你需要看看框架是如何实现的。看看这个mysqli_real_escape_string函数。

此外,您需要验证$ id变量实际上是一个整数以防止SQL注入,因为mysqli_real_escape_string自身并不完全安全。为此使用intval

在你的情况下,你只需要确保$ id是一个整数值。 因此,您应该将您的代码更改为如下所示:

public function deleteItem($id) { 
    $delId = intval($id); 

    if ($delId <= 0) 
     return /* fail since ID is invalid */; 

    $sqlQuery = "DELETE FROM items WHERE id=$delId;"; 

    $result = $this->getDbManager() -> executeQuery ($sqlQuery); 
}