PHP PDO dynamic update query to MYSQL

前端 未结 1 1649
予麋鹿
予麋鹿 2021-01-29 09:52

I have a form with an image upload and text inputs. it keeps replacing the profile_picture field with NULL. Therefore, I\'m trying to create a dynamic update query,

相关标签:
1条回答
  • 2021-01-29 10:45

    Below is the solution, where an input is empty, it'll use the existing data in that field and will accept not only $_POST variables, but all variables.

    // the list of allowed field names
    $allowed = ["profile_picture","first_name","last_name", "phone_number", "nationality", "years_experience", "data" ];
    
    // initialize an array with values:
    $params = [];
    
    // initialize a string with `fieldname` = :placeholder pairs
    $setStr = "";
    
    // loop over source data array
    foreach ($allowed as $key)
    {
        if (!empty([$key]) || $key != "" || $key != NULL)
        {
    
            if($GLOBALS[$key] != NULL){
    
            $setStr .= "`$key` = :$key ,";
            $params[$key] = $GLOBALS[$key];
    
            }else{
    
            $setStr .= "`$key` = $key ,";
    
            }
    
        }else{
    
    
    
        }
    }
    $setStr = rtrim($setStr, ",");
    
    $params['id'] = $_SESSION['user_id'];
    
    $dbh->prepare("UPDATE 001_user_table_as SET $setStr WHERE id = :id")->execute($params);
    
    0 讨论(0)
提交回复
热议问题