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


How to neatly "build" large sql queries made up of a large number of variables

首先,对不起,如果已经问过这个问题了。
我环顾四周,但找不到任何答案,或者我搜索了错误的单词。

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

这就是我的意思:

$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;";

再一次,这工作正常,但必须有一种更简单(和更整洁(的方法。
有人有解决方案吗?

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

$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';