正在尝试转换为mysqli。这几天我得到了很大的帮助,谢谢。我的下一个问题是当使用左连接时如何转换。
mysql工作代码
$q1 = 'SELECT * FROM earth LEFT JOIN cities ON (cities.countryid4city = earth.countryid) GROUP BY countryid ORDER by countryid';
$q2 = 'SELECT * FROM cities ORDER BY cityname';
$mytable1 = mysql_query($q1);
$mytable2 = mysql_query($q2);
echo mysql_error();
mysql_close();
$numrows_table1 = mysql_numrows($mytable1);
$numrows_table2 = mysql_numrows($mytable2);
$i = 0;
while ($i < $numrows_table1){
$countryid = mysql_result($mytable1,$i,'countryid');
$countryname = mysql_result($mytable1,$i,'countryname');
print "<br><br>Country is " . $countryname . ", and these cities are in it";
$j = 0;
while ($j < $numrows_table2){
$countryid4city = mysql_result($mytable2,$j,'countryid4city');
$cityname = mysql_result($mytable2,$j,'cityname');
if ($countryid4city == $countryid){
print "<br><br>" . $cityname;
}
$j++;
}
$i++;
}
输出如预期(请注意,此网站删除了此页中的换行符,但它们仍然存在)。
Country is USA, and these cities are in it
New York
San Francisco
Country is England, and these cities are in it
Chelsea
Clapham
London
Country is Sweden, and these cities are in it
Lidingö
Stockholm
破坏mysqli转换(遵循相同的逻辑,我想)
$q1 = 'SELECT * FROM earth LEFT JOIN cities ON (cities.countryid4city = earth.countryid) GROUP BY countryid ORDER by countryid';
$q2 = 'SELECT * FROM cities ORDER BY cityname';
$mytable1 = mysqli_query($conned, $q1);
$mytable2 = mysqli_query($conned, $q2);
mysqli_close($conned);
while($row1 = mysqli_fetch_assoc($mytable1)){
$countryid = $row1['countryid'];
$countryname = $row1['countryname'];
print "<br><br>Country is " . $countryname . ", and these cities are in it";
while($row2 = mysqli_fetch_assoc($mytable2)){
$countryid4city = $row2['countryid4city'];
$cityname = $row2['cityname'];
if ($countryid4city == $countryid){
print "<br><br>" . $cityname;
}
}
}
输出
Country is USA, and these cities are in it
New York
San Francisco
Country is England, and these cities are in it
Country is Sweden, and these cities are in it
它只从第二个表中选取左联接值作为第一个表的第一个值。我错过了什么?我想我可能没有一个理想的解决方案,以工作的mysql版本。
非常感谢您的帮助。谢谢。
1条答案
按热度按时间u4dcyp6a1#
mysql_result
使结果集作为索引数组可用。奥托mysqli_fetch_assoc
从结果中检索一行。您可以通过将光标移到内部循环之前记录集的开头来解决问题:这只会增加运行第二个查询来检索您已经知道的数据的愚蠢性。将第一个查询更改为
丢失第二个查询和内部循环。每次countryid更改时,在输出中插入一个新的country头。