mysqli转换

xwbd5t1u  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(283)

正在尝试转换为mysqli。这几天我得到了很大的帮助,谢谢。我的下一个问题是当使用左连接时如何转换。
mysql工作代码

  1. $q1 = 'SELECT * FROM earth LEFT JOIN cities ON (cities.countryid4city = earth.countryid) GROUP BY countryid ORDER by countryid';
  2. $q2 = 'SELECT * FROM cities ORDER BY cityname';
  3. $mytable1 = mysql_query($q1);
  4. $mytable2 = mysql_query($q2);
  5. echo mysql_error();
  6. mysql_close();
  7. $numrows_table1 = mysql_numrows($mytable1);
  8. $numrows_table2 = mysql_numrows($mytable2);
  9. $i = 0;
  10. while ($i < $numrows_table1){
  11. $countryid = mysql_result($mytable1,$i,'countryid');
  12. $countryname = mysql_result($mytable1,$i,'countryname');
  13. print "<br><br>Country is " . $countryname . ", and these cities are in it";
  14. $j = 0;
  15. while ($j < $numrows_table2){
  16. $countryid4city = mysql_result($mytable2,$j,'countryid4city');
  17. $cityname = mysql_result($mytable2,$j,'cityname');
  18. if ($countryid4city == $countryid){
  19. print "<br><br>" . $cityname;
  20. }
  21. $j++;
  22. }
  23. $i++;
  24. }

输出如预期(请注意,此网站删除了此页中的换行符,但它们仍然存在)。

  1. Country is USA, and these cities are in it
  2. New York
  3. San Francisco
  4. Country is England, and these cities are in it
  5. Chelsea
  6. Clapham
  7. London
  8. Country is Sweden, and these cities are in it
  9. Lidingö
  10. Stockholm

破坏mysqli转换(遵循相同的逻辑,我想)

  1. $q1 = 'SELECT * FROM earth LEFT JOIN cities ON (cities.countryid4city = earth.countryid) GROUP BY countryid ORDER by countryid';
  2. $q2 = 'SELECT * FROM cities ORDER BY cityname';
  3. $mytable1 = mysqli_query($conned, $q1);
  4. $mytable2 = mysqli_query($conned, $q2);
  5. mysqli_close($conned);
  6. while($row1 = mysqli_fetch_assoc($mytable1)){
  7. $countryid = $row1['countryid'];
  8. $countryname = $row1['countryname'];
  9. print "<br><br>Country is " . $countryname . ", and these cities are in it";
  10. while($row2 = mysqli_fetch_assoc($mytable2)){
  11. $countryid4city = $row2['countryid4city'];
  12. $cityname = $row2['cityname'];
  13. if ($countryid4city == $countryid){
  14. print "<br><br>" . $cityname;
  15. }
  16. }
  17. }

输出

  1. Country is USA, and these cities are in it
  2. New York
  3. San Francisco
  4. Country is England, and these cities are in it
  5. Country is Sweden, and these cities are in it

它只从第二个表中选取左联接值作为第一个表的第一个值。我错过了什么?我想我可能没有一个理想的解决方案,以工作的mysql版本。
非常感谢您的帮助。谢谢。

u4dcyp6a

u4dcyp6a1#

mysql_result 使结果集作为索引数组可用。奥托 mysqli_fetch_assoc 从结果中检索一行。您可以通过将光标移到内部循环之前记录集的开头来解决问题:

  1. mysqli_result_data_seek ($mytable2, 0);
  2. while($row2 = mysqli_fetch_assoc($mytable2)){

这只会增加运行第二个查询来检索您已经知道的数据的愚蠢性。将第一个查询更改为

  1. ...ORDER by countryid, cityname";

丢失第二个查询和内部循环。每次countryid更改时,在输出中插入一个新的country头。

相关问题