PHP PDO dynamic update query to MYSQL

家住魔仙堡 提交于 2021-02-17 07:08:55

问题


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, where if one value is empty it's excluded from the query altogether.

Any help is appreciated.

IMAGE UPLOAD:

if (!empty($_FILES['profile_picture']) && $_FILES['profile_picture']['error'] == UPLOAD_ERR_OK) {

    // Rename the uploaded file
    $uploadName = $_FILES['profile_picture']['name'];
    $tmp_name = $_FILES['profile_picture']['tmp_file'];
    $ext = strtolower(substr($uploadName, strripos($uploadName, '.')+1));
    $filename = round(microtime(true)).mt_rand().'.'.$ext;

if (move_uploaded_file($_FILES['profile_picture']['tmp_name'],'../profile_picutres/'. $filename)) {

}

}

UPDATE QUERY:

$stmt = $dbh->prepare("UPDATE 001_user_table_as SET profile_picture=:profile_picture, first_name=:first_name, last_name=:last_name, phone_number=:phone_number, nationality=:nationality, years_experience=:years_experience, data=:data WHERE id=:id");

 $stmt->bindParam(':profile_picture', $filename);
 $stmt->bindParam(':first_name', $first_name);
 $stmt->bindParam(':last_name', $last_name);
 $stmt->bindParam(':phone_number', $phone_number);
 $stmt->bindParam(':nationality', $nationality);
 $stmt->bindParam(':years_experience', $years_experience);
 $stmt->bindParam(':data', $cv_data);
 $stmt->bindParam(':id', $user_id);

if($stmt->execute()){
$response["message"] = 'success';   
}else{
$response["message"] = 'error'; 
$errors++;
} 

回答1:


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);


来源:https://stackoverflow.com/questions/47507118/php-pdo-dynamic-update-query-to-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!