SocialEngine数据库查询清理

时间:2012-03-30 17:43:39

标签: php mysql socialengine

好的,我需要明确一点,在PHP / MySQL方面我不是天才我所知道的是当我做出比以往更困难的事情时。我想知道是否有人可以查看以下代码集并告诉我如何简化它。所以我知道如何解决它,并在下次做。

$link = mysql_connect('localhost', 'username', 'password'); 
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db('fetish')) {
    die('Could not select database: ' . mysql_error());
}
$userid = $this->translate($this->viewer()->getIdentity());
$result = mysql_query("SELECT photo_id FROM engine4_users WHERE user_id = $userid");
if (!$result) {
die('Could not query:' . mysql_error());
}
$photoid = mysql_result($result, 0);
$result1 = mysql_query("SELECT storage_path FROM engine4_storage_files WHERE parent_file_id = $photoid");
if (!$result1) {
    die('Could not query:' . mysql_error());
}
$avatar = mysql_result($result1, 0);
if (!$avatar) {
   $avatar = "application/themes/musicbox-red/images/nophoto_user_thumb_icon.png";<br>
}
$result2 = mysql_query("SELECT country FROM engine4_user_fields_search WHERE item_id = $userid");
if (!$result2) {
    die('Could not query:' . mysql_error());
}
$country = mysql_result($result2, 0);

所以基本上我在一天结束时需要的是以下变量$ userid $ avatar $ country

感谢任何可以提前帮助的人。

赖安

1 个答案:

答案 0 :(得分:0)

我认为这就是你所需要的。你必须使用连接。尝试:

$userid = $this->translate($this->viewer()->getIdentity());
$result = mysql_query("
SELECT u.user_id, f.country as `country`, s.storage_path as `spath` FROM engine4_users as u
LEFT JOIN engine4_storage_files as s ON u.photo_id = s.parent_file_id 
JOIN engine4_user_fields_search as f ON u.user_id = f.item_id
WHERE u.user_id = $userid
");
while($row = mysql_fetch_array($result)) {
  // Do your code logic here
  $country = $row['country'];
  if($row['spath']) {
    $avatar = "application/themes/musicbox-red/images/nophoto_user_thumb_icon.png";
  }
  else
    $avatar = NULL;
}