dongtu4559 2014-08-08 11:18
浏览 32
已采纳

PDO使用可选值进行更新

I am trying to build a query string for updating some user info. My problem is password is optional (they update something, but not their password), client is optional and phone is optional.

I started with something like this

<?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 : ''
    ));
.....
?>

I am thinking there has to be a better way to do this with PDO. Also, I still have not incorporate into the query yet the WHERE id = :idOfTheUserIamEditing

  • 写回答

1条回答 默认 最新

  • dtmwnqng38644 2014-08-08 11:58
    关注

    Your code looks fine to me, there isn't so many other ways to accomplish what you are trying to achieve. One thing I suggest is to build your array of parameters as you check the optional fields, this saves you from doing a "ton of if statement":

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

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部