2011-01-27 75 views
0

基本上我有兩個文件,group.php和class.Groups.phpPHP MySQL的取打印幫助

我想打印出來張貼到該組的最後20級的消息,但是我不出來,因爲我我對這很新鮮!任何幫助歡迎。

我遇到的問題是我調用的函數是在一個類中。只是不知道如何做while循環和打印。

也歡迎關於我的代碼結構&佈局的建議和反饋。

謝謝。

class.Groups.php

<?php include("config.php"); 

// Get Group Details 

class Group { 

var $groupID; 
var $groupName; 
var $groupDescription; 
var $groupMessage; 

function group_details($ID) { 
    $group_details = mysql_query("SELECT * FROM Groups WHERE GroupID = '".$ID."' LIMIT 1"); 
    if (mysql_num_rows($group_details) == 1) { 
    $group_details_row = mysql_fetch_assoc($group_details); 
    $this->groupID = $group_details_row ['GroupID']; 
    $this->groupName = $group_details_row ['Name']; 
    $this->groupDescription = $group_details_row ['Description']; 
    } 
} 

function group_member($ID) { 
    $group_member = mysql_query("SELECT * FROM GroupMembers WHERE GroupID = '".$ID."' AND UserID = '".$_SESSION['UserID']."' LIMIT 1"); 
    if (mysql_num_rows($group_member) == 1) { 
    return 1; 
    } 
    else { 
    return null; 
    } 
} 

function group_messages($ID) { 
    $group_messages = mysql_query("SELECT * FROM GroupMessages INNER JOIN Users ON Users.UserID = GroupMessages.UserID WHERE GroupID = '".$ID."' LIMIT 20"); 
    while ($group_messages_row = mysql_fetch_assoc($group_messages)) { 
    $this->groupMessage = $group_messages_row['Message']; 
    } 
} 

} 

?> 

group.php

<?php include("includes/class.Groups.php"); 

$group = new Group; 
$group->group_details($_GET['ID']); 

if ($_SESSION['LoggedIn'] == 1) { 
if ($group->group_member($_GET['ID'])) { 
    include("includes/header.php"); ?> 
    <div id="container"> 
    <div id="menu"><?php include("includes/sidebar.php"); ?></div> 
    <div id="main"> 
    <h2><?php echo $group->groupName; ?></h2> 
    <p><?php echo $group->groupDescription; ?></p> 
    <h3>Messages</h3> 
    <?php 
    while ($group->group_messages($_GET['ID'])) { 
     echo $group->groupMessage; 
    } 
    ?> 
    </div> 
    </div> 
<?php 
} 
else { 
    echo "You are not member of this group."; 
} 
} 
?> 

回答

1

您不能使用$group->group_messages()while內,這是因爲:

  1. 它不返回任何東西(返回結果爲false
  2. 它經歷中的所有行一個電話,而你希望它在同一時間返回一行

你可以重寫你的類代碼收集在一個變量的所有行,使用foreach循環返回它和它的迭代

// class.Groups.php 
function group_messages($ID) { 
    $group_messages = array(); 
    $group_messages = mysql_query("SELECT * FROM GroupMessages INNER JOIN Users ON Users.UserID = GroupMessages.UserID WHERE GroupID = '".$ID."' LIMIT 20"); 
    while ($group_messages_row = mysql_fetch_assoc($group_messages)) { 
     $group_messages[] = $group_messages_row['Message']; 
    } 
    return $group_messages; 
} 

// groups.php 
<h3>Messages</h3> 
<?php 
    foreach ($group->group_messages($_GET['ID']) as $group_message) { 
     echo $group_message; 
    } 
?> 
0

你似乎在這盤一個額外的代碼大括號:

<?php 
        while ($group->group_messages($_GET['ID'])) { 
         echo $group->groupMessage; } 
       } ?> 
+0

}只是在錯誤的地方,反正沒有造成問題。 – ritch