0

我知道这个主题之前已经介绍过,并且我已经阅读了大约十几个 stackoverflow 提供的链接。没有一个符合我的需要。

我有 4 个使用 PHP 查询类似数据的 mysql 查询,我想将其降低到一个查询,并可能将结果放入我可以访问的数组中。这是我当前的代码。

 $id = $row[post_id];
    $resulttwo = mysql_query("SELECT meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` = 'length' ");
    $temptwo = mysql_fetch_array($resulttwo);       
    $length[$id] = $temptwo[0];

    $id = $row[post_id];
    $resultthree = mysql_query("SELECT meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` = 'location_city' ");
    $tempthree = mysql_fetch_array($resultthree);
    $trailcity[$id] = $tempthree[0];

    $id = $row[post_id];
    $resultfour = mysql_query("SELECT meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` = 'location_state' ");
    $tempfour = mysql_fetch_array($resultfour);
    $trailstate[$id] = $tempfour[0];

    $id = $row[post_id];
    unset($tempfour);
    $resultfour = mysql_query("SELECT meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` = 'difficulty' ");
    $tempfour = mysql_fetch_array($resultfour);
    $difficulty[$id] = $tempfour[0].' difficulty';`
4

2 回答 2

5

这应该有效:

$id = $row[post_id];
$result = mysql_query("SELECT meta_key, meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` IN ('length', 'location_city', 'location_state', 'difficulty')");
$temp = mysql_fetch_assoc($result);

数组$temp将包含meta_keymeta_value应该能够像这样调用的$temp[length]。您可以检查整个阵列print_r($temp);

您还应该停止使用mysql_函数编写新代码,因为它们已被弃用并使用mysqli_orPDO代替。

于 2012-11-30T16:51:17.637 回答
0

这应该足够了,因为您只关心每个查询中的第一行。

SELECT meta_value FROM wp_postmeta WHERE post_id = $id AND meta_key IN ("length", "location_city", "location_state", "difficulty") LIMIT 4;

妈的太晚了!:/

于 2012-11-30T16:59:29.390 回答