PDO使用可选值进行更新

时间:2014-08-08 19:18:13

标签: php mysql pdo

我正在尝试构建一个用于更新某些用户信息的查询字符串。我的问题是password是可选的(他们会更新某些内容,但不会更新密码),client是可选的,phone是可选的。

我从这样的事情开始

<?php
$sql = "UPDATE users SET username = :username, name = :name, email = :email ";

if (isset($request->password)) $sql .= ',password = :password';

if (isset($request->client)) $sql .= ',client = :client';

if (isset($request->phone)) $sql .= ',phone = :phone'

$q = $db->prepare($sql);
try
{
    $q->execute(array(
        "username"      => $request->username,
        "password"      => (isset($request->password)) ? md5($request->password) : '', //--not working yet, I know
        "name"          => $request->name,
        "client"        => (isset($request->client)) ? $request->client : '',
        "email"         => $request->email,
        "phone"         => (isset($request->phone)) ? $request->phone : ''
    ));
.....
?>

我认为必须有更好的方法来使用PDO。此外,我还没有将WHERE id = :idOfTheUserIamEditing

纳入查询

1 个答案:

答案 0 :(得分:3)

您的代码对我来说很好,没有其他方法可以实现您想要实现的目标。我建议的一件事是在检查可选字段时构建参数数组,这样可以避免执行大量的if语句&#34;:

$sql = "UPDATE users SET username = :username, name = :name, email = :email ";

$params = array();
//mandatory
$params[':username'] = $request->username;
$params[':name'] = $request->name;
$params[':email'] = $request->email;

//optional
if (isset($request->password)){
    $sql .= ',password = :password';
    $params[':password'] = $request->password;
}

if (isset($request->client)){
    $sql .= ',client = :client';
    $params[':client'] = $request->client;
}

if (isset($request->phone)){
    $sql .= ',phone = :phone';
    $params[':phone'] = $request->phone;
} 


try
{
    $q = $db->prepare($sql);
    $q->execute(array($params);
    ...