Branndon
Branndon

Reputation: 505

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

Upvotes: 0

Views: 193

Answers (2)

Niclas Larsson
Niclas Larsson

Reputation: 1317

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! :/

Upvotes: 0

Kermit
Kermit

Reputation: 34054

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.

Upvotes: 5

Related Questions