2012-02-03 72 views
0

我有两个问题,请帮助我。把一张桌子放在二维数组中并显示它

  1. 在PHP/MySQL中我有一个很长的查询,我写它在7行。现在I 想要运行它,并将该查询(表格)的结果作为2d 数组放入变量中。我该怎么做 ?
  2. 在将查询结果作为二维数组放入一个变量后,现在我要如何在 html页面中以表格的形式显示我的查询结果?

感谢

** * ** ** * **

 $database_host = "localhost"; 
    $database_username = "root"; 
    $database_password = ""; // FOR ME!!! 

    $connection = mysql_connect("$database_host", "$database_username", "$database_password") or die("Could't connect to database!"); 
    if(!mysql_select_db("football_db", $connection)) 
     die("Could't select database!"); 

    // Sanitizing leagueName input 
    $leagueName = strtolower(strval($_POST[ 'leagueName' ])); 
    $leagueName = stripslashes($leagueName); 

    // Sanitizing seasonName input 
    $seasonName = strtolower(strval($_POST[ 'seasonName' ])); 
    $seasonName = stripslashes($seasonName); 



    $query = "SELECT cl.club_name , cr.played , cr.matches_won AS W , cr.matches_lose AS L , 
     (cr.played - (cr.matches_won + cr.matches_lose)) AS D , 
     cr.goals_for AS GF , cr.goals_against AS GA , (cr.goals_for - cr.goals_against) AS GD , 
     (cr.matches_won*3 + (cr.played - (cr.matches_won + cr.matches_lose))) AS PTS 
    FROM ClubsRecords AS cr , Clubs AS cl , Seasons AS se , leagues AS le 
    WHERE le.league_type='$leagueName' AND se.season_name ='$seasonName' AND 
     se.league_id = le.league_id AND cr.club_id = cl.club_id AND cr.season_id = se.season_id 
    ORDER BY PTS DESC;"; 
+0

你尝试过?????? – 2012-02-03 13:41:31

+0

是的,我GOOGLE了它,但我不知道我怎么能把查询的结果放在二维数组中,并显示它。 – 2012-02-03 13:43:49

+0

无论如何,如果我们要帮助你,我们需要数据的例子,这个问题太笼统了。 – Vyktor 2012-02-03 13:44:05

回答

1
$result = mysql_query($query); 
$rows = array(); 

while($row = mysql_fetch_assoc($result)) { 
    $rows[] = $row; 
} 

echo json_encode($rows); 

,我认为这种CAN H elp你。

+0

感谢您的帮助,但我想显示该2d数组像一个表中的HTML页。使用“json_encode”,它将显示查询结果,如set not table。 – 2012-02-03 14:09:43

0

走出去的肢体有明显的答案没有真正了解你在寻找什么样的二维数组为:

$twoDimArray = array(); 
$result = mysql_query($query); 

if ($result !== false) 
{ 
    while ($row = mysql_fetch_assoc($result)) 
    { 
     $twoDimArray[] = $row; 
    } 
} 
1
/* Question 1: */ 

    $res = mysql_query($query); 
    $rows = array(); 
    while ($row = mysql_fetch_assoc($res)) { 
     $rows[] = $row; 
    } 

    // $rows is your 2d-array 

/* Question 2: */ 

    echo "<table>\n"; 

    // print the rownames 
    $keys = array_keys($rows); 
    echo "<tr>\n"; 
    foreach($keys as $key) { 
     echo " <td>$key</td>\n"; 
    } 
    echo "</tr>\n"; 

// print the values 
echo "<tr>\n"; 
foreach($rows as $row) { 
    print('<tr>'); 
    foreach($row as $key => $value){ 
     echo " <td>$value</td>\n"; 
     } 
    print('</tr>'); 
} 
echo "</tr>\n"; 
echo "</table>\n"; 
+0

你的第二个答案没有显示2d数组作为表。 – 2012-02-03 14:25:29

+0

我的不好。改变它! tnx m8 – 2012-02-03 14:44:09