简体   繁体   中英

Combining multiple MYSQL queries into one with PHP

I know this subject has been covered before, and I've read about a dozen of the links provided by stackoverflow. None match my need.

I have 4 mysql queries using PHP for similar data, I'd like to lower that to one query and maybe put the results in an array that I can access. Here is my current code.

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

This should work:

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

Array $temp will contain the meta_key along with the meta_value which you should be able to call like so $temp[length] . You can check the entire array with print_r($temp);

You should also stop writing new code using mysql_ functions as they are being deprecated and use mysqli_ or PDO instead.

This should be sufficient as you only care about the first row in each query.

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

Damn too late! :/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM