在php的while循环中使用Select Query

问题描述:

当我尝试在 while 循环中执行第二个选择查询时,我试图从 2 个表中打印一些数据
我的查询是

I am trying to Print some data from 2 tables when i try to execute 2nd select query inside while loop its not showing any result
My query is

$query=mysql_query("SELECT * FROM buses");
echo "<table border='1'>";
echo "<tr>";
echo "<td>Sno</td>";
echo "<td>Route #</td>";
echo "<td>Bus _Type</td>";
echo "<td>Timing</td>";
echo "<td>From</td>";
echo "</tr>";
while($row=mysql_fetch_array($query)){
echo "<tr>";
echo "<td>"."<center>".$row['sno']."</center>"."</td>";
echo "<td>"."<center>".$row['Route']."</center>"."</td>";
echo "<td>"."<center>".$row['Bus_type']."</center>"."</td>";
echo "<td>"."<center>".substr($row['Timing'],0,5)."</center>"."</td>";
$route=$row['Route'];
$query2=mysql_query("SELECT fromcity FROM routes WHERE Route= '$route' ");
$row2=mysql_fetch_array($query2);
echo "<td>"."<center>".$row2['fromcity']."</center>"."</td>";

路由表

公交车表

结果

您可以继续使用您的解决方案,但为了效率起见,您不应该在循环内执行 SELECT,而应该使用 SQL JOIN.

You can continue with your solution but for efficiency sake, you shouldn't be doing a SELECT inside a loop, you should be using an SQL JOIN.

您的查询应该连接 Route 字段上的两个表:

Your query should be joining the two tables on the Route field:

SELECT * FROM buses b
INNER JOIN routes r ON b.Route = r.Route;

循环内不需要额外的查询,因为您可以从此查询访问 fromcity.您可能希望在 SELECT 中专门声明字段,而不是使用 *.

No extra queries will be needed inside the loop as you'll have access to the fromcity from this query. You may want to specifically declare the fields in the SELECT rather than using *.