我遇到了mysql更新的问题,我不知道如何修复它

liwlm1x9  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(328)

我是mysql的新手。这是我的代码块:

public function updateTable($obj, $column_names, $table_name, $bannerid) {

    $c = (array) $obj;
    $id = $bannerid;
    $keys = array_keys($c);
    $columns = '';
    $values = '';
    foreach($column_names as $desired_key){ // Check the obj received. If blank insert blank into the array.
       if(!in_array($desired_key, $keys)) {
            $$desired_key = '';
        }else{
            $$desired_key = $c[$desired_key];
        }
        $columns = $columns.$desired_key.',';
        $values = $values."'".$$desired_key."',";
    }
    //$query = "INSERT INTO ".$table_name."(".trim($columns,',').") VALUES(".trim($values,',').")";
    //mysql_query("UPDATE blogEntry SET content = '$udcontent', title = '$udtitle' WHERE id = $id");
    $query = "UPDATE ".$table_name." SET "."(".trim($columns,',').") = VALUES(".trim($values,',').")" ."WHERE id = '$id'" ;
    $r = $this->conn->query($query) or die($this->conn->error.__LINE__);

    if ($r) {
        $new_row_id_update = $this->conn->insert_id;
        return $new_row_id_update;
        } else {
        return NULL;
    }
}

下面是我得到的错误:
sql语法有错误;请查看与您的mysql服务器版本对应的手册,以了解使用near'(image\u url,intro)=values('800bf5f59a1d13c8.jpg',',sd,cfcjaklewfh ewiuofejkfdh'的正确语法,该语法位于第1100行

zf9nrax1

zf9nrax11#

关于查询结构,sgedes是正确的。试试这个。您应该回显$query以确保它正确构建。

public function updateTable($obj, $column_names, $table_name, $bannerid) {

    $c = (array) $obj;
    $id = $bannerid;
    $keys = array_keys($c);
   $subquery='';
   foreach($column_names as $desired_key){
       // Check the obj received. If blank insert blank into the array.
   if(!in_array($desired_key, $keys)) {
        $$desired_key = '';
    }else{
        $$desired_key = $c[$desired_key];
    }
    $subquery.=$desired_key."='".$$desired_key ."',";
}
//remove trailing common
$query="UPDATE ".$table_name." SET " substr(subquery,0,-1)." WHERE id = '$id'" ;
$r = $this->conn->query($query) or die($this->conn->error.__LINE__);

   if ($r) {
    $new_row_id_update = $this->conn->insert_id;
    return $new_row_id_update;
    } else {
    return NULL;
   }

}

相关问题