Building the Index Page for a PHP Email Application - Retrieving Messages (
Page 3 of 4 )
Next, the messages are retrieved from the database to be displayed in the table:
//get them out and display
//ALL newly downloaded messages will have checked set to 0
$query_msgs = "select * from messages WHERE checked =
'0'";
$re = mysql_query($query_msgs);
$n = mysql_num_rows($re);
if($n > 0){
while($r = mysql_fetch_array($re)){
?> <td></td>
<td valign="top" class="list"><? if($r['checked']==1){?>
<a href="view.php?mid=<?=$r['msg_id'];?>"
class="email2"><?=$r['from']; ?></a>
<? }else{ ?>
<a href="view.php?mid=<?=$r['msg_id'];?>&em=<?
$email; ?>" class="email"><?=$r['from'];?></a>
<? } ?> </a></td>
<td valign="top" class="list"><?=$r['subject']; ?></td>
<td valign="top" class="list"><?=$r['date']; ?></td>
<td valign="top" class="list"><a href="#"
class="menu">Delete</a></td>
</tr>
<? }
}?>
<?
}//end for
}//end check
If there are no new messages, in other words, the $numEmails variable is zero, then the script retrieves the old messages stored in the database:
else{//there are no new messages, so get the old messages from database
?>
<?
include "connect.php";
$query_email = "SELECT user_id FROM user WHERE user_id = '".$_SESSION['userid']."'";
$result_email= mysql_query($query_email);
$num_email= mysql_num_rows($result_email);
if($num_email > 0 ){
while($res = mysql_fetch_array($result_email)){
$user = $res['user_id'];
}
}else{
echo mysql_error();
}
//get all msgs
$query_msgs = "select * from messages";
$re = mysql_query($query_msgs);
$n = mysql_num_rows($re);
if($n > 0){
while($r = mysql_fetch_array($re))
{
?>
<tr class="td">
<td><? if($r['checked']==1){?> <img src="images/env.gif" />
<? }else{ ?>
<? echo $r['checked'];}?>
</td>
<td valign="top" class="list"><? if($r['checked']==1){?>
<a href="view.php?mid=<?=$r
['msg_id'];?>" class="email2"><?=$r['from']; ?></a>
<? }else{ ?>
<a href="view.php?mid=<?=$r['msg_id'];?>"
class="email"><?=$r['from'];?></a>
<? } ?> </a></td>
<td valign="top" class="list"><?=$r['subject']; ?></td>
<td valign="top" class="list"><?=$r['msg_date']; ?
></td>
<td valign="top" class="list"><a href="delete.php?
mid=<?=$['msg_id']?>" class="menu">Delete</a></td>
</tr>
<?
}//end 2nd while
}
}
Last but not least, I've made this code available to the script as optional, because you might want to delete all the messages from the mail server after inserting them into the database. This will save you from downloading the same messages when you return to the index page:
/*
//delete emails from server
if($numEmails > 0){
$num_msg = imap_num_msg($stream);
for ( $i=1; $i<=$num_msg; $i++ ) {
imap_delete($stream, $i);
}
imap_expunge($stream);
*/
?>
</table>