dongtu4559 2014-08-08 19: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 19: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);
        ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?