Steven Kinnear
Steven Kinnear

Reputation: 412

How to return variable from a function

This might be straight forward but im lost

I have this piece of code

$query = "
SELECT torrents.id, 
       torrents.anon, 
       torrents.announce, 
       torrents.parentcat, 
       torrents.category, 
       torrents.vip, 
       torrents.`4ever`, 
       torrents.leechers, 
       torrents.nfo, 
       torrents.seeders, 
       torrents.name, 
       torrents.times_completed, 
       torrents.`size`, 
       torrents.added, 
       torrents.comments, 
       torrents.numfiles, 
       torrents.filename, 
       torrents.owner, 
       torrents.safe, 
       torrents.external, 
       torrents.freeleech, 
       categories_parent.cat_parent_name, 
       categories_parent.image_parent, 
       categories.name                                    AS cat_name, 
       categories.image                                   AS cat_pic, 
       users.username, 
       users.privacy, 
       Round(torrents.ratingsum / torrents.numratings, 1) AS rating 
FROM   torrents 
       LEFT JOIN categories 
         ON category = categories.id 
       LEFT JOIN categories_parent 
         ON parentcat = categories_parent.cat_parent_id 
       LEFT JOIN users 
         ON torrents.owner = users.id 
WHERE  visible = 'yes' 
       AND safe = 'yes' 
       AND banned = 'no' 
ORDER  BY id DESC 
LIMIT  5 ";
$res = SQL_Query_exec($query);
if (mysql_num_rows($res)) {
    torrenttable1($res);

Now My function code produces a table, If i want a value from the function i.e row[id] to use in my orginal code how do i send it back from my function and how do i pick it up so i can continue using the value.

function torrenttable($res) {
global $site_config, $CURUSER, $THEME, $LANGUAGE;  //Define globals

if ($site_config["MEMBERSONLY_WAIT"] && $site_config["MEMBERSONLY"] && in_array($CURUSER["class"], explode(",",$site_config["WAIT_CLASS"]))) {

$wait = $site_config["WAITA"];
}

// Columns
$cols = explode(",", $site_config["torrenttable_columns"]);
$cols = array_map("strtolower", $cols);
$cols = array_map("trim", $cols);
$colspan = count($cols);
// End

// Expanding Area
$expandrows = array();
if (!empty($site_config["torrenttable_expand"])) {
    $expandrows = explode(",", $site_config["torrenttable_expand"]);
    $expandrows = array_map("strtolower", $expandrows);
    $expandrows = array_map("trim", $expandrows);
}
// End



while ($row = mysql_fetch_assoc($res)) {
    $id = $row["id"];

    print("<li><div id=row>");

$x = 1;

foreach ($cols as $col) {
    switch ($col) {
        case 'category':
            print("<div id=left>");
            if (!empty($row["cat_name"])) {
                print("<a href=\"torrents-search.php?cat=" . $row["category"] . "\">");

                if (!empty($row["cat_pic"]) && $row["cat_pic"] != "")
                    print("<img border=\"0\"src=\"" . $site_config['SITEURL'] . "/images/categories/" . $row["cat_pic"] . "\" alt=\"" . $row["cat_name"] . "\" />");
                else
                    print("$row[cat_name]");
                print("</a>");
            } else
                print("-");
            print("</div>\n");
        break;
        //km added for parent picture
        case 'parent':
            print("<div id=left>");
            if (!empty($row["cat_parent_name"])) {
                //print("<a href=\"torrents-details.php?id=$id&amp;hit=1\">");
                print("<a href=\"torrents-search.php?cat1=" . $row["parentcat"] . "\">");
                                    if (!empty($row["image_parent"]) && $row["image_parent"] != "")
                    print("<img border=\"0\"src=\"" . $site_config['SITEURL'] . "/images/categories/" . $row["image_parent"] . "\" alt=\"" . $row["cat_parent_name"] . "\" />");
                else
                    print("$row[cat_parent_name]");
                print("</a>");
            } else
                print("-");
            print("</div>\n");
        break;

        //kn end for parent picture//


        case 'name':
            $char1 = 60; //cut name length 
            $smallname = htmlspecialchars(CutName($row["name"], $char1));
            $dispname = "<b>".$smallname."&nbsp;</b>";
            $time = date('jS M Y, g:ia', utc_to_tz_time($row['added']));

            //balloon mod

          $bimg = @mysql_fetch_array(@mysql_query("SELECT image1 FROM torrents WHERE id=$id"));
         $balon =($bimg["image1"] ? "$site_config[SITEURL]/uploads/images/" . htmlspecialchars($bimg["image1"]) : "images/nocover.jpg");

                 print("<div id=left>".(count($expandrows)?"<a href=\"java script: klappe_torrent('t".$row['id']."')\"><img border=\"0\" src=\"".$site_config["SITEURL"]."/images/plus.gif\" id=\"pict".$row['id']."\" alt=\"Show/Hide\" class=\"showthecross\"></a>":"")."&nbsp;<a href=\"torrents-details.php?id=$id&amp;hit=1\" onMouseover=\"ddrivetip('<img border=0 width=120 src=$balon>')\"; onMouseout=\"hideddrivetip()\">$dispname</a><br><font color=grey><small>&nbsp;Added:&nbsp; ".$time."</font></small></div>");               
            //end balloon mod




        //  print("<td class='ttable_col$x' nowrap='nowrap'>".(count($expandrows)?"<a href=\"javascript: klappe_torrent('t".$row['id']."')\"><img border=\"0\" src=\"".$site_config["SITEURL"]."/images/plus.gif\" id=\"pict".$row['id']."\" alt=\"Show/Hide\" class=\"showthecross\" /></a>":"")."&nbsp;<a title=\"".$row["name"]."\" href=\"torrents-details.php?id=$id&amp;hit=1\">$dispname</a><br><font color=grey><small>&nbsp;Added:&nbsp; ".$time."</font></small> </td>");
            //vip

            break;
            case 'vip':
            $dispname1 ="";
              if ($row["vip"] == "y") {
                            $dispname1 = $dispname1 . "<img src='images/vip/vipsmall.png' / border=0  title=\"Vip\" >";
                            }
            //vip end
             if ($row["4ever"] == "y") {
                            $dispname1 = $dispname1 . "<img src='images/vip/4evervipsmall.png' / border=0  title=\"Vip 4Ever\" >";
                            }

            $last_access = $CURUSER["last_browse"];
            $time_now = gmtime();
            if ($last_access > $time_now || !is_numeric($last_access))
                $last_access = $time_now;
            if (sql_timestamp_to_unix_timestamp($row["added"]) >= $last_access)
                $dispname .= "<b><font color='#ff0000'> - (".T_("NEW")."!)</font></b>";

            if ($row["freeleech"] == 1)
                $dispname1 .= " <img src='images/vip/freeleechsmall.png' border='0' title=\"Freeleech\" />";
            print("<div id=left><center>$dispname1</center></div>");
        break;

                    case 'uploader':
            echo "<div id=left>";
            if (($row["anon"] == "yes" || $row["privacy"] == "strong") && $CURUSER["edit_torrents"] != "yes")
                echo "Anonymous";
            elseif ($row["username"])
                echo "<a href='account-details.php?id=$row[owner]'>$row[username]</a>";
            else
                echo "Unknown";
            echo "</div>";
        break;
        case 'comments':
            print("<div id=left><font size='1' face='verdana'><a href='comments.php?type=torrent&amp;id=$id'>" . number_format($row["comments"]) . "</a></font></div>\n");
        break;

        case 'size':
            print("<div id=left>".mksize($row["size"])."</div>\n");
        break;

        case 'seeders':
            print("<div id=left><font color='green'><b>".number_format($row["seeders"])."</b></font></div>\n");
        break;
        case 'leechers':
        $lots1 = $row['id'];

            print("<div id=left><font color='#ff0000'><b>" . number_format($row["leechers"]) . "</b>$lots1</font></div>\n");
        break;
                    case 'wait':
            if ($wait){
                $elapsed = floor((gmtime() - strtotime($row["added"])) / 3600);
                if ($elapsed < $wait && $row["external"] != "yes") {
                    $color = dechex(floor(127*($wait - $elapsed)/48 + 128)*65536);
                    print("<div id=row><a href=\"faq.php#section46\"><font color=\"$color\">" . number_format($wait - $elapsed) . " h</font></a></div>\n");
                } else
                    print("<td class='ttable_col$x' align='center'>--</td>\n");
            }
        break;
        case 'rating':
            if (!$row["rating"])
                $rating = "<img src='images/rating/0.png' border=0>";
            else
                $rating = "<a title='$row[rating]/5'>".ratingpic($row["rating"])."</a>";
                //$rating = ratingpic($row["rating"]);
                 //$srating .= "$rpic (" . $row["rating"] . " out of 5) " . $row["numratings"] . " users have rated this torrent";
            print("<div id=left>$rating</div>");
        break;

        //km added book marks
        case 'Bookmark':
         if ($variant == "bookmarks") 
        echo "<div id=left><a href='bookmarktakedel.php?bookmarkid=$id' title='Delete'><img src='images/delchat.gif'                border='0' width='10px' alt='delete' title='delete' /></a></div>";
                    break;          
                    //end bookmarks


    }
    if ($x == 2)
        $x--;
    else
        $x++;
}





    //Wait Time Check
    if ($wait && !in_array("wait", $cols)) {
        $elapsed = floor((gmtime() - strtotime($row["added"])) / 3600);
        if ($elapsed < $wait && $row["external"] != "yes") {
            $color = dechex(floor(127*($wait - $elapsed)/48 + 128)*65536);
            print("<div id=left><a href=\"faq.php\"><font color=\"$color\">" . number_format($wait - $elapsed) . " h</font></a></div>\n");
        } else
            print("<div id=left>--</div>\n");
        $colspan++;
        if ($x == 2)
            $x--;
        else
            $x++;
    }
    //$lots = $row['id'];

            print("</div></li>");

    //Expanding area
    if (count($expandrows)) {
        print("<tr><td class='ttable_col$x' colspan='$colspan'><div id=\"kt".$row['id']."\" style=\"margin-left: 2px; display: none;\">");
        print("<table width='100%' border='0' cellspacing='0' cellpadding='0'>");
        foreach ($expandrows as $expandrow) {
            switch ($expandrow) {
                case 'size':
                    print("<tr><td><b>".T_("SIZE")."</b>: ".mksize($row['size'])."</td></tr>");
                break;
                case 'speed':
                    if ($row["external"] != "yes" && $row["leechers"] >= 1){
                        $speedQ = SQL_Query_exec("SELECT (SUM(downloaded)) / (UNIX_TIMESTAMP('".get_date_time()."') - UNIX_TIMESTAMP(started)) AS totalspeed FROM peers WHERE seeder = 'no' AND torrent = '$id' ORDER BY started ASC");
                        $a = mysql_fetch_assoc($speedQ);
                        $totalspeed = mksize($a["totalspeed"]) . "/s";
                        print("<tr><td><b>".T_("SPEED").":</b> $totalspeed</td></tr>");
                    }
                break;
                case 'added':
                    print("<tr><td><b>".T_("ADDED").":</b> ".date("d-m-Y \\a\\t H:i:s", utc_to_tz_time($row['added']))."</td></tr>");
                break;
                case 'tracker':
                if ($row["external"] == "yes")
                    print("<tr><td><b>".T_("TRACKER").":</b> ".htmlspecialchars($row["announce"])."</td></tr>");
                break;
                case 'completed':
                    print("<tr><td><b>".T_("COMPLETED")."</b>: ".number_format($row['times_completed'])."</td></tr>");
                break;
            }
        }
            print("</table></div></td></tr>\n");
    }
    //End Expanding Area


}

Upvotes: 1

Views: 285

Answers (5)

sandeep
sandeep

Reputation: 2234

return torrenttable1($res);

in function:

function torrenttable1($res)
{
.
return $xyz;
}

Upvotes: 0

fourreux
fourreux

Reputation: 125

I don't quite understand what you're trying to do but:

A function encapsulates data. i.e. what is inside cannot and should not be accessed. It's like a black box where you put stuff in and at the other end the function gives something back to you.

The function can always give you something back via return. But this you can only do once! Once the function returns something, it stops executing.

Of course, you can return an array for example. This way you're able to return multiple values. But again: the moment you return something the function stops and the calling code resumes ...

Upvotes: 2

PiotrDomo
PiotrDomo

Reputation: 1045

Why don't you put your code in class and create variables/array of data for SQL returned results? In this case you can access them any time and pretty anywhere around your php file.

Upvotes: 0

Ingmar Boddington
Ingmar Boddington

Reputation: 3500

function torrenttable1($res) {

     //[Table stuff]

    return $value;
}

The call would be:

$returnedVar = torrenttable1($res);

...a little difficult to understand the question.

Upvotes: 3

qpaycm
qpaycm

Reputation: 932

function func1($a) {
  return $a;
}
$a=5;
echo func1($a);

Upvotes: 0

Related Questions