简体   繁体   中英

How to exclude MySQL query from my loop (limit unnecessary queries)

I'm asking MySQL for data, but it slows down the whole script. Yet I have no idea how to get this out of a loop. I tried converting it to PHP array but honestly after day of tries I failed.

<?php

$id = '1';

include_once 'include_once/connect.php';

for ($x = 1; $x <= 5; $x++) {
for ($y = 1; $y <= 5; $y++) {

    $xy = $x."x".$y;

    $pullMapInfo = "SELECT value FROM mapinfo WHERE id='".$id."' AND xy='".$xy."'";
    $pullMapInfo2 = mysql_query($pullMapInfo) or die('error here');

    if ($pullMapInfo3 = mysql_fetch_array($pullMapInfo2)) {
        #some code
    } else {
        #some code
    }
}
}

?>

How to get MySQL query $pullMapInfo2 out of loop to shorten loading it by asking once?

If you want to fire script on your localhost you can c&p whole thing :-)

I'm not sure what you have in your table, but considering you are basically looping through virtually everything in it, I'd say do a single query for the given Id and then sort out what you need from the larger dataset.

Especially if you are always pulling back essentially the complete dataset for each id, there's no reason to even bother with the IN query, just pull it all back into a single PHP array, and then iterate through that as needed.

Use a MySQL IN clause

<?php

$id = '1';

include_once 'include_once/connect.php';

// first we create an array with all xy
$array = array();
for ($x = 1; $x <= 5; $x++) {
    for ($y = 1; $y <= 5; $y++) {
        $xy = $x."x".$y;
        $array[] = $xy;
    }
}

$in = "'" . implode("', '", $array) . "'";
$pullMapInfo = "SELECT xy, value FROM mapinfo WHERE id='".$id."' AND xy IN ({$in})";
$pullMapInfo2 = mysql_query($pullMapInfo) or die('error here');

// we create an associative array xy => value
$result = array();
while (($pullMapInfo3 = mysql_fetch_assoc($pullMapInfo2)) !== false) {
    $result[ $pullMapInfo3['xy'] ] = $pullMapInfo3['value'];
}


// we make a loop to display expected output
foreach ($array as $xy)
{
    if (array_key_exists($xy, $result)) {
        echo '<div class="castle_array" style="background-image: url(tiles/'.$result[$xy].'.BMP)" id="'.$xy.'">'. $result[$xy] .'</div>';
    } else {
        echo '<div class="castle_array" id="'.$xy.'"></div>';
    }
    echo '<div class="clear_both"></div>';
}

?>

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