简体   繁体   中英

Returning Array From PHP Function

What is wrong with this code? I am trying to return an array and use it in the caller function.

function my_subjects()
        {   
            $all_my_teams=my_teams();
            $k=0;
            $_subjects=array();
            while($team=mysql_fetch_assoc($all_my_teams))
            {
                $q="SELECT $this->user_field FROM $team";
                $r=mysql_query($q);

                while($i=mysql_fetch_assoc($r))
                {
                    $_subjects[k++]=$i;
                }
            }                   

            return $_subjects;
        }

Note: the function my_teams() returns the value similar to the $r variable which is used through all_my_teams variable. it contains all the names of teams.

  1. Turn up error_reporting to see if your code is generating errors.
  2. Check if your query is successful if( ! $r=mysql_query($q) ) { die(mysql_error()); } if( ! $r=mysql_query($q) ) { die(mysql_error()); }
  3. var_dump($_subjects); to see if the data is what you expect it to be.
  4. Maybe actually tell us what's going wrong? You've just posted a block of code and told us "it doesn't work." which isn't terribly indicative of a problem.
  5. $k is irrelevant, just use $_subjects[]=$i; . [wouldn't cause an error, just easier]
  6. Stop using mysql_* functions and port your code to PDO or MySQLi to:
    • Benefit from parameterized queries which can help protect against SQL injection.
    • Stop everyone on SO starting an unrelated argument in the comments about it.
while($i=mysql_fetch_assoc($r))
                {
                    $_subjects[k++]=$i;
                }

Here you also have to provide a field name for $i . Something like

while($i=mysql_fetch_assoc($r))
                {
                    $_subjects[$k++]=$i["field_name"];
                }

Array returning part is just fine.

Edit: Your variable k was missing a $ sign as well.

$_subjects[$k++] = $i;

should be fine, since you're using mysql_fetch_assoc() $i will contain an associative array of the result set.

If this is returning an empty array (is that the correct problem?), you should double check that your sql is correct and actually returning data/data that you expect.

Edit: Like Hanky Panky mentioned, 'k' is missing a $ sign in your code - that is likely to be your problem - PHP should be throwing a parse error for that one, so make sure you have error_reporting() enabled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM