如何在一个while循环中从两个表中获取数据?

时间:2014-01-16 10:05:01

标签: php

有没有办法只使用一个while循环从两个表中获取数据?

这是代码:

<?php

$sql=mysql_query("select *from pm where send_to='$_GET[name]' limit $offset, $rowsperpage");

$sql2=mysql_query("select *from pm_reply where send_to='$_GET[name]' limit $offset, $rowsperpage");

$start_from = $offset + 1; 
echo "<ol start='$start_from'>";
while($rows=mysql_fetch_assoc($sql))

{

echo"<li>From: <a href='profile.php?name=$rows[send_by]'>$rows[send_by]</a><br><br><a style='text-decoration:none; font-size:14pt;' href='view_pm.php?name=$_GET[name]&pm=$rows[subject]'>$rows[subject]</a></li>"; 

echo "<hr>";
echo "<br>";
}

while($rows2=mysql_fetch_assoc($sql2))
{
echo"<li>From: <a href='profile.php?name=$rows2[replied_by]'>$rows2[replied_by]</a><br><br><a style='text-decoration:none; font-size:14pt;' href='view_pm.php?name=$_GET[name]&pm=$rows2[subject]'>$rows2[subject]</a></li>"; 

echo "<hr>";
echo "<br>"
}

echo "</ol>";
?>

3 个答案:

答案 0 :(得分:0)

您的工作方式不正确 使用 加入两个表格 然后进行连接查询 让生活变得轻松:)

由于

答案 1 :(得分:0)

使用内部联接或多重选择来执行结果集变量 Select A.date1, B.date2 from table1 A, table2 B where ... 那么你可以将其视为单个结果集 或者,如果要在日期之间搜索数据,则可以使用句子“之间” Select sales from table where dates between 'date1' and 'date2'

答案 2 :(得分:0)

没有什么可以阻止你写

while(($rows=mysql_fetch_assoc($sql)) OR ($rows2=mysql_fetch_assoc($sql2)))
{
    if ($rows)
    {
        // ...
    }
    if ($rows2)
    {
        // ...
    }
}

但是这段代码&#34;闻起来&#34;