如何巧妙地“构建”由大量变量组成的大型SQL查询

时间:2014-12-12 07:58:33

标签: php

首先,对不起,如果已经被问到这一点 我环顾四周但却找不到任何答案,或者我正在用错误的词语搜索。

我需要使用PHP执行一个很长的SQL查询。它需要更新大量变量。

这就是我的意思:

$user = json_decode($stringWithJson);

$reallyLongSqlQuery = "UPDATE `profile` SET `userid` = '{$user->userid}', `name` = '{$user->username}', `lastlogoff` = '{$user->userlastlogoff}', `profileurl` = '{$user->userprofileurl}', `avatar` = '{$user->useravatar}', `avatarmedium` = '{$user->useravatarmedium}', `useravatarfull` = '{$user->useravatarfull}', `state` = '{$user->userprofilestate}', `realname` = '{$user->userrealname}', `timecreated` = '{$user->userprofilecreatedunix}' WHERE `id` = 1;";

mysql_query($reallyLongSqlQuery);

这样可以正常工作,但是单行代码很多。有什么方法可以tidy这个吗?

示例:

$reallyLongSqlQuery = "UPDATE `profile` SET `userid` = '" . $user->userid . 
    "', `name` = '" . $user->username . 
    "', `lastlogoff` = '" . $user->userlastlogoff . 
    "', `profileurl` = '" . $user->userprofileurl . 
    "', `avatar` = '" . $user->useravatar .  
    "', `avatarmedium` = '" . $user->useravatarmedium . 
    "', `useravatarfull` = '" . $user->useravatarfull . 
    "', `state` = '" . $user->userprofilestate . 
    "', `realname` = '" . $user->userrealname . 
    "', `timecreated` = '" . $user->userprofilecreatedunix . 
    "' WHERE `id` = 1;";

这不会在一条巨线上飞出屏幕,但在我看来它看起来更加混乱。

我采用的另一种方法是预先定义所有变量,如下所示:

$userid = $user->userid;
$username = $user->username;
$userlastlogoff = $user->userlastlogoff;
$userprofileurl = $user->userprofileurl;
$useravatar = $user->useravatar;
$useravatarmedium = $user->useravatarmedium;
$useravatarfull = $user->useravatarfull;
$userprofilestate = $user->userprofilestate;
$userrealname = $user->userrealname;
$userprofilecreatedunix = $user->userprofilecreatedunix;

$reallyLongSqlQuery = "UPDATE `profile` SET `userid` = '{$userid}', `name` = '{$username}', `lastlogoff` = '{$userlastlogoff}', `profileurl` = '{$userprofileurl}', `avatar` = '{$useravatar}', `avatarmedium` = '{$useravatarmedium}', `useravatarfull` = '{$useravatarfull}', `state` = '{$userprofilestate}', `realname` = '{$userrealname}', `timecreated` = '{$userprofilecreatedunix}' WHERE `id` = 1;";

再次,这很好但是必须有一种更容易(和更整洁)的方式来做到这一点 有人有解决方案吗?

1 个答案:

答案 0 :(得分:1)

当然你应该使用绑定,而不是普通的查询字符串,但是数组在你的情况下会有所帮助:

$data['userid']         = $user->userid;
$data['name']           = $user->username;
$data['lastlogoff']     = $user->userlastlogoff;
$data['profileurl']     = $user->userprofileurl;
$data['avatar']         = $user->useravatar; 
$data['avatarmedium']   = $user->useravatarmedium;
$data['useravatarfull'] = $user->useravatarfull;
$data['state']          = $user->userprofilestate;
$data['realname']       = $user->userrealname;
$data['timecreated']    = $user->userprofilecreatedunix;

foreach ($data as $column => $value)
{
  $updates[] = "$column = '$value' "; // value should be escaped!
}

$reallyLongSqlQuery = 'UPDATE profile SET '.
                      implode(',',$updates).
                      ' WHERE id = 1';