php pdo连接mysql 查询,PHP PDO动态更新查询到MYSQL

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

}

解决方案

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值