a) 我无法使用以下脚本 + 示例数据重现该行为
<?php
mysql_connect('localhost', 'localonly', 'localonly') or die(mysql_error());
mysql_select_db('test') or die(mysql_error());
setup();
$locationzips = array(34110,34145,34135,33928,33901,33904);
foreach ($locationzips as $key => $zip) {
$getcities = mysql_query("SELECT * FROM tmp_us WHERE code = '$zip'") or die(mysql_error());
echo 'test zip: '.$zip."\n";
while($row = mysql_fetch_assoc($getcities)) {
$city = $row['city'];
echo 'test city: '.$city."\n";
}
}
function setup() {
mysql_query('
CREATE TEMPORARY TABLE tmp_us (
id int auto_increment,
city varchar(64),
code varchar(16),
primary key(id)
)
') or die(mysql_error());
for($code=33901; $code<=34145; $code++) {
foreach(range('a','d') as $foo) {
$city = $code.'_'.$foo;
$stmt = sprintf("INSERT INTO tmp_us (city,code) VALUES('%s','%s')", $city, $code);
mysql_query($stmt) or die(mysql_error());
}
}
}
b)例如使用 IN 运算符时,您不需要多个查询
<?php
mysql_connect('localhost', 'localonly', 'localonly') or die(mysql_error());
mysql_select_db('test') or die(mysql_error());
setup();
$locationzips = array(34110,34145,34135,33928,33901,33904);
$stmt = sprintf("SELECT * FROM tmp_us WHERE code IN ('%s') ORDER BY code", join("','", $locationzips));
$getcities = mysql_query($stmt) or die(mysql_error());
$current_code = null;
while( false!==($row=mysql_fetch_assoc($getcities)) ) {
if ( $current_code!=$row['code'] ) {
$current_code = $row['code'];
echo 'zip: ', $current_code, "\n";
}
echo ' city: ', $row['city'], "\n";
}
function setup() {
mysql_query('
CREATE TEMPORARY TABLE tmp_us (
id int auto_increment,
city varchar(64),
code varchar(16),
primary key(id)
)
') or die(mysql_error());
for($code=33901; $code<=34145; $code++) {
foreach(range('a','d') as $foo) {
$city = $code.'_'.$foo;
$stmt = sprintf("INSERT INTO tmp_us (city,code) VALUES('%s','%s')", $city, $code);
mysql_query($stmt) or die(mysql_error());
}
}
}
印刷
zip: 33901
city: 33901_a
city: 33901_b
city: 33901_c
city: 33901_d
zip: 33904
city: 33904_d
city: 33904_c
city: 33904_b
city: 33904_a
zip: 33928
city: 33928_a
city: 33928_b
city: 33928_c
city: 33928_d
zip: 34110
city: 34110_d
city: 34110_c
city: 34110_b
city: 34110_a
zip: 34135
city: 34135_d
city: 34135_c
city: 34135_b
city: 34135_a
zip: 34145
city: 34145_a
city: 34145_b
city: 34145_c
city: 34145_d
c) mysql 扩展被标记为已弃用。改用PDO之类的东西