我向MySQL请求数据,但它减慢了整个脚本的运行速度。然而,我不知道如何让它走出循环。我尝试将其转换为PHP数组,但老实说,经过一天的尝试,我失败了。
<?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
}
}
}
?>如何让MySQL查询$pullMapInfo2跳出循环,缩短一次查询加载时间?
如果你想在你的本地主机上启动脚本,你可以c&p全部:-)
发布于 2012-09-09 18:57:20
使用MySQL IN子句
<?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>';
}
?>发布于 2012-09-09 19:02:01
我不确定您的表中有什么,但考虑到您基本上遍历了表中的几乎所有内容,我建议您对给定的Id执行一次查询,然后从较大的数据集中整理出所需的内容。
特别是如果您总是从本质上为每个id拉回完整的数据集,那么甚至没有理由为IN查询而烦恼,只需将其拉回到单个PHP数组中,然后根据需要遍历该数组。
https://stackoverflow.com/questions/12338397
复制相似问题