如何在一个表中显示两个mysql查询的两个结果?

时间:2014-10-06 18:10:07

标签: php mysql html-table

这是我的代码,结果是错误的。我想在第一列中显示第一个查询的结果,在第二列中显示第二个查询的结果,但两个结果都在一(第一)列中。如何在不更改查询的情况下进行此操作?

/*
    username        username
    username_a_1    username_b_1
    username_a_1    username_b_4
    username_a_2    username_b_1
    username_a_2    username_b_4
    username_a_3    username_b_5
    username_a_4    username_b_2
    username_a_4    username_b_3
    username_a_5    username_b_1
    username_a_5    username_b_4
*/
<html>
<head></head>
<table border="1" >
    <tr>
        <th>USERNAME</th>
        <th>USERNAME</th>
    </tr>
<?php
include'db_connect.php';

$query1='SELECT username FROM contacts_a ';
$query_run1=mysql_query($query1);

$query2="SELECT contacts_a.username,contacts_b.username FROM contacts_a LEFT JOIN contacts_b ON contacts_a.level=contacts_b.level";
$query_run2=mysql_query($query2);



 while($query_array1=mysql_fetch_assoc($query_run1)){
        foreach($query_array1 as $index => $names){

            echo   '<tr>
                        <td>'.(($names == NULL )? 'NULL': $names).'</td>
                   </tr>'; 
        }//end of foreach

  }//end of while

  while($query_array2=mysql_fetch_assoc($query_run2)){

        foreach($query_array2 as $index => $names){

             echo   '<tr>
                      <td>'.(($names == NULL )? 'NULL': $names).'</td>
                    </tr>'; 
        }//end of foreach

  }//end of while




?>
</table>

</html>

2 个答案:

答案 0 :(得分:0)

试试这个:

// Select the data, all together now. The difference is we'll give it a name
$query2="SELECT contacts_a.username as firstTableName, 
                contacts_b.username as secondTableName 
           FROM contacts_a 
      LEFT JOIN contacts_b 
             ON contacts_a.level = contacts_b.level";

// Execute the Query
$query_run2=mysql_query($query2);

// Loop over our results...
while($query_array1 = mysql_fetch_assoc($query_run1)) {
    // We're going to use this again, give it a good name
    $firstName = ($query_array1['firstTableName'] == NULL)   ? 'NULL' :
        $query_array1['firstTableName'];
    $secondName = ($query_array1['secondTableName'] == NULL) ? 'NULL' :
        $query_array1['secondTableName'];

    // Put out a new table row
    echo   '<tr>';
        // And our first TD...
       echo '<td>' . firstName  .'</td>';
       echo '<td>' . secondName .'</td>';
    echo   '</tr>'; 

// End our loop
} // So Long and Thanks for All the Fish!

其他一些想法:Don't use MySQL!您现在也可以摆脱第一个查询,因为它是多余的。关于您的NULL检查,如果数据作为空字符串进入会发生什么?通常我检查null和空引号:''或“”只是为了确保我得到我想要的东西。

免责声明:我实际上没有尝试过这个,而且我使用PDO,所以我的MySQL语法可能会回来并读取MySQL数组错误!

答案 1 :(得分:-2)

$qa1 = mysql_fetch_assoc($query_run1);
$qa2 = mysql_fetch_assoc($query_run2);

do {
  echo   '<tr>
    <td>'.(current($qa1) == NULL ? 'NULL': current($qa1)).'</td>
    <td>'.(current($qa2) == NULL ? 'NULL': current($qa2)).'</td>
  </tr>'; 
} while( next($qa1) || next($qa2) );