Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function php with while loop

Tags:

function

php

Hello i am trying to make function with while loop in php but cant getting write here is my code

 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 is

$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 am not getting all values just getting one value please help thx

like image 674
Harinder Avatar asked Jun 08 '26 00:06

Harinder


1 Answers

The return statement is terminating your loop and exiting the function.

To get all values, add them to an array in the loop, and then 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 on, a function is only able to return once (except for some special circumstances that you should not worry about). Therefore, the first time your function comes across a return statement, it returns the value and exits.

This functionality of return can often be used to your advantage. For example:

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);
}
like image 188
xbonez Avatar answered Jun 10 '26 16:06

xbonez