Php function with while loop

Hi, I am trying to make a function with a while loop in php, but I can not write my code here

 function mail_detail($mail_detail){

    $data= mysql_query("select * from messages where messages.to = '$mail_detail' and to_viewed = 0 ORDER BY messages.id DESC");
    while ($result= mysql_fetch_array($data)){
    return $result;
    }

}

and out put

$mail_detail= mail_detail($userid)
echo '<li class="read">

               <a href="#">
                 <span class="message">'. $mail_detail['title'].'</span>
                    <span class="time">
                       January 21, 2012
                   </span>
                                </a>
        </li>';

I do not get all the values, just getting one value, please help THX

+3
source share
3 answers

The statement returncompletes your loop and exits the function.

To get all the values, add them to the array in a loop and return the array. Like this:

$results = array();

while ($result = mysql_fetch_array($data)) {
    $results[] = $result;   
}

return $results;

on the side that receives the array

$msgArray = mail_detail($mail_detail);

foreach($msgArray as $msg) {
    //use $msg
}

To add, a function can only return once (except in special circumstances that you should not worry about). Therefore, at the first call to the return statement, a value is returned and completed.

This feature returncan often be used to your advantage. For instance:

function doSomething($code = NULL) 
{
    if ($code === NULL) {
        return false;
    }

    //any code below this comment will only be reached if $code is not null
    // if it is null, the above returns statement will prevent control from reaching 
    // this point

    writeToDb($code);
}
+8
function mail_detail($mail_detail){
    $returnArr = array();
    $data= mysql_query("select * from messages where messages.to = '$mail_detail' and to_viewed = 0 ORDER BY messages.id DESC");
    while ($result= mysql_fetch_array($data)){
        $returnArr[] = $result;
    }
    return $returnArr;

}

, wil. , xbones, !

0

harinder, Function(mysql_fetch_array($data))return the array. This means yours $resultis an array, so when you get the page $resulton the watch page, you need to extract it using foreachlook for example:

foreach($result as $item)
 {
   echo $item->user(<-here you have to write the column name ,that you want to retrieve)
 } 

Therefore, you can get all the results in an array.

0
source

All Articles