簡體   English   中英

PDO 更新函數中的錯誤

[英]Error in PDO Update Function

$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

沒有像$fldquery這樣$fldquery東西

$sql = substr($fldquery,0,strlen($fldquery)-1);
              ^^^                  ^^^

因此您的查詢只是

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

這導致

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

這只是問題之一,當您修復錯字並在那里輸入正確的變量名稱時,它將被修復。 但是,如果您閱讀本文,則會發現更大的問題

如何防止 PHP 中的 SQL 注入?

這可能與您在數值周圍放置單引號有關,這不是必需的,並且可能會破壞您的查詢,因為您的數據庫可能將其視為字符串而不是數字。

$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 注入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM