将表放在2d数组中并显示它

时间:2012-02-03 13:38:00

标签: php mysql database phpmyadmin

我有两个问题,请帮助我。

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

    ** * * 示例 * ** < EM> * **

            $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;";
    

3 个答案:

答案 0 :(得分:1)

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

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

echo json_encode($rows);

我认为这可以帮助你。

答案 1 :(得分: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";

答案 2 :(得分:0)

在没有真正知道你正在寻找什么样的二维数组的情况下,用一个明显的答案走出一条肢体:

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

if ($result !== false)
{
    while ($row = mysql_fetch_assoc($result))
    {
        $twoDimArray[] = $row;
    }
}