PHP PDO 动态更新查询到 MYSQL [英] PHP PDO dynamic update query to MYSQL

查看:51
本文介绍了PHP PDO 动态更新查询到 MYSQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含图片上传和文本输入的表单.它不断用 NULL 替换 profile_picture 字段.因此,我正在尝试创建一个动态更新查询,如果一个值为空,它将完全从查询中排除.

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.

感谢任何帮助.

图片上传:

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

}

}

更新查询:

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

推荐答案

下面是解决方案,如果输入为空,它将使用该字段中的现有数据并且不仅接受 $_POST变量,但所有变量.

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

这篇关于PHP PDO 动态更新查询到 MYSQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆