PDO更新功能出错

时间:2016-04-01 07:57:06

标签: php mysql pdo

$table="menu_permission";
$field = array('permission'=>$mnuprmis);
$ob->update($table,$field,'staff_id',$stfid);


public function update($table, $fields, $wherefield, $wherefieldvalues) 
    {
        $sql = "update $table set";
        foreach ( $fields as $fieldname => $sfieldvalue )
            $sql .=  $fieldname."= '".$sfieldvalue."',";
            $sql = substr($fldquery,0,strlen($fldquery)-1);
            $sql .=" where $wherefield = '$wherefieldvalues'";
        $q = $this->conn->prepare($sql);
        $q->execute();
        return true;
    }

错误

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: 
Syntax error or access violation: 1064 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 'where staff_id = '1'' at line 1' 
in G:\xampp\htdocs\live\Billing Suryas\model\DBConfig.php:171 
Stack trace: #0 G:\xampp\htdocs\live\Billing Suryas\model\DBConfig.php(171): PDOStatement->execute() 
#1 G:\xampp\htdocs\live\Billing Suryas\pages\permission_pages.php(257): Connection->update('menu_permission', Array, 'staff_id', '1') 
#2 {main} thrown in G:\xampp\htdocs\live\Billing Suryas\model\DBConfig.php on line 171

2 个答案:

答案 0 :(得分:3)

没有像$fldquery

这样的怪异事物
$sql = substr($fldquery,0,strlen($fldquery)-1);
              ^^^                  ^^^

因此您的查询仅为

 $sql .=" where $wherefield = '$wherefieldvalues'";

结果是

 where staff_id = '1'   // This is your COMPLETE query

这只是其中一个问题,当您修复拼写错误并在其中输入正确的变量名称时,它将得到解决。但是,如果你阅读这个

,那么更大的问题将是显而易见的

How can I prevent SQL injection in PHP?

答案 1 :(得分:-1)

这可能与您在数字值周围放置单引号这一事实有关,这不是必需的,可能会破坏您的查询,因为您的数据库可能会将其视为字符串而不是数字。

$table="menu_permission";
$field = array('permission'=>$mnuprmis);
$ob->update($table,$field,'staff_id',$stfid);


public function update($table, $fields, $wherefield, $wherefieldvalues) 
    {
        //
        // COMPILE QUERY
        $sql = "update $table set ";
        $col_values_array = array();
        foreach ( $fields as $fieldname => $sfieldvalue ) {
            $value = is_numeric($sfieldvalue) ? $sfieldvalue : "'$sfieldvalue'";
            $col_values_array[] =  "$fieldname = $value";
        }
        $sql .= implode("," , $col_values_array);
        $sql .= " where $wherefield = '$wherefieldvalues'";
        //
        // EXECUTE QUERY
        //$q = $this->conn->prepare($sql); --> not required when not using parametrised queries
        //$q->execute(); --> not required when not using parametrised queries
        $this->conn->query($sql);
        return true;
    }

还要考虑使用预准备语句来防止SQL注入。