使用PHP将多个MYSQL查询合并为一个

Bra*_*don 0 php mysql

我知道之前已经讨论过这个主题,我已经阅读了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';`
Run Code Online (Sandbox Code Playgroud)

Ker*_*mit 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);
Run Code Online (Sandbox Code Playgroud)

阵列$temp将包含meta_key与沿着meta_value你应该能够像这样调用$temp[length].你可以检查整个阵列print_r($temp);

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